ngram
listlengths
0
67.8k
[ "if bucket is None or len(bucket) == 0: n += 1 return n", "all buckets # and reinsert key=>values for bucket in oldBuckets: if bucket is", "return n def get_num_empty_buckets(self): n = 0 for bucket in self._buckets: if bucket", "a hash function' self._buckets = [None] * length self.hash_len = length self.hash_fn =", "def _shrink(self): # length = self.hash_len pass def __repr__(self): return '<Hashmap %r>' %", "Double size of buckets self.hash_len = self.hash_len * 2 # New max len", "len(bucket) >= self.change_len: # print('growing', 'num buckets: ', len(self._buckets)) self._grow() def _grow(self): #", "pos = self._hash(key) bucket = self._buckets[pos] if bucket is None: return None return", "%r>' % self._buckets def __len__(self): n = 0 for bucket in self._buckets: if", "LinkedList() bucket.put(key, val) else: bucket.put(key, val) if len(bucket) >= self.change_len: # print('growing', 'num", "in oldBuckets: if bucket is None: continue for (key, val) in bucket: self.put(key,", "def __init__(self, hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You must provide", "key=>values for bucket in oldBuckets: if bucket is None: continue for (key, val)", "in self._buckets: if bucket is None: shortest = 0 b = None break", "for bucket in self._buckets: if not bucket: continue n += len(bucket) return n", "= 0 b = None break l = len(bucket) if shortest == 0:", "self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You must provide a hash function' self._buckets", "'<Hashmap %r>' % self._buckets def __len__(self): n = 0 for bucket in self._buckets:", "= None break l = len(bucket) if shortest == 0: shortest = l", "self._buckets: if bucket is None or len(bucket) == 0: n += 1 return", "= length self.hash_fn = hash_fn # Max items per bucket self.change_len = length", "hashmap returns the value in the map if it exists \"\"\" pos =", "shortest == 0: shortest = l if shortest >= l: shortest = l", "new bucket holder oldBuckets = self._buckets self._buckets = [None] * self.hash_len # Iterate", "5 def _hash(self, key): return self.hash_fn(key) % self.hash_len def put(self, key, val): pos", "None self._buckets[pos] = None self.num_values -= 1 return node.val def _shrink(self): # length", "continue n += len(bucket) return n def get_num_empty_buckets(self): n = 0 for bucket", "val) in bucket: self.put(key, val) def get(self, key): pos = self._hash(key) bucket =", "5 # new bucket holder oldBuckets = self._buckets self._buckets = [None] * self.hash_len", "= self.hash_len / 5 # new bucket holder oldBuckets = self._buckets self._buckets =", "returns the value in the map if it exists \"\"\" pos = self._hash(key)", "0: n += 1 return n def get_longest_bucket(self): longest = 0 b =", "self.hash_len def put(self, key, val): pos = self._hash(key) bucket = self._buckets[pos] if bucket", "self._buckets = [None] * self.hash_len # Iterate through all buckets # and reinsert", "bucket = LinkedList() bucket.put(key, val) else: bucket.put(key, val) if len(bucket) >= self.change_len: #", "is None: shortest = 0 b = None break l = len(bucket) if", "oldBuckets = self._buckets self._buckets = [None] * self.hash_len # Iterate through all buckets", "def get_num_empty_buckets(self): n = 0 for bucket in self._buckets: if bucket is None", "_shrink(self): # length = self.hash_len pass def __repr__(self): return '<Hashmap %r>' % self._buckets", "bucket return longest def get_shortest_bucket(self): shortest = 0 b = None for bucket", "shortest = 0 b = None break l = len(bucket) if shortest ==", "is None: continue l = len(bucket) if longest < l: longest = l", "val) def get(self, key): pos = self._hash(key) bucket = self._buckets[pos] if bucket is", "_grow(self): # Double size of buckets self.hash_len = self.hash_len * 2 # New", "break l = len(bucket) if shortest == 0: shortest = l if shortest", "bucket: continue n += len(bucket) return n def get_num_empty_buckets(self): n = 0 for", "get(self, key): pos = self._hash(key) bucket = self._buckets[pos] if bucket is None: return", "% self._buckets def __len__(self): n = 0 for bucket in self._buckets: if not", "if bucket is None: self._buckets[pos] = bucket = LinkedList() bucket.put(key, val) else: bucket.put(key,", "if bucket is None: shortest = 0 b = None break l =", "for bucket in self._buckets: if bucket is None or len(bucket) == 0: n", "(key, val) in bucket: self.put(key, val) def get(self, key): pos = self._hash(key) bucket", "self.hash_len * 2 # New max len for buckets self.change_len = self.hash_len /", "len(bucket) if shortest == 0: shortest = l if shortest >= l: shortest", "def __len__(self): n = 0 for bucket in self._buckets: if not bucket: continue", "def _hash(self, key): return self.hash_fn(key) % self.hash_len def put(self, key, val): pos =", "continue l = len(bucket) if longest < l: longest = l b =", "[None] * length self.hash_len = length self.hash_fn = hash_fn # Max items per", "in a hashmap returns the value in the map if it exists \"\"\"", "map \"\"\" def __init__(self, hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You", "Max items per bucket self.change_len = length / 5 def _hash(self, key): return", "for buckets self.change_len = self.hash_len / 5 # new bucket holder oldBuckets =", "= None for bucket in self._buckets: if bucket is None: continue l =", "provide a hash function' self._buckets = [None] * length self.hash_len = length self.hash_fn", "\"\"\" pos = self._hash(key) node = self._buckets[pos] if node is None: return None", "for bucket in oldBuckets: if bucket is None: continue for (key, val) in", "self.change_len = self.hash_len / 5 # new bucket holder oldBuckets = self._buckets self._buckets", "0 assert hasattr(hash_fn, '__call__'), 'You must provide a hash function' self._buckets = [None]", "self.hash_len # Iterate through all buckets # and reinsert key=>values for bucket in", "return node.val def _shrink(self): # length = self.hash_len pass def __repr__(self): return '<Hashmap", "New max len for buckets self.change_len = self.hash_len / 5 # new bucket", "max len for buckets self.change_len = self.hash_len / 5 # new bucket holder", "== 0: n += 1 return n def get_longest_bucket(self): longest = 0 b", "= self._buckets self._buckets = [None] * self.hash_len # Iterate through all buckets #", "self.hash_fn = hash_fn # Max items per bucket self.change_len = length / 5", "the map if it exists \"\"\" pos = self._hash(key) node = self._buckets[pos] if", "self._buckets[pos] if bucket is None: self._buckets[pos] = bucket = LinkedList() bucket.put(key, val) else:", "self._buckets[pos] if bucket is None: return None return bucket.get(key) def delete(self, key): \"\"\"", "\"\"\" character holding hash map \"\"\" def __init__(self, hash_fn, length=100): self.num_values = 0", "+= len(bucket) return n def get_num_empty_buckets(self): n = 0 for bucket in self._buckets:", "b = None for bucket in self._buckets: if bucket is None: continue l", "= [None] * self.hash_len # Iterate through all buckets # and reinsert key=>values", "bucket.put(key, val) if len(bucket) >= self.change_len: # print('growing', 'num buckets: ', len(self._buckets)) self._grow()", "= bucket = LinkedList() bucket.put(key, val) else: bucket.put(key, val) if len(bucket) >= self.change_len:", "self._buckets[pos] = bucket = LinkedList() bucket.put(key, val) else: bucket.put(key, val) if len(bucket) >=", "get_num_empty_buckets(self): n = 0 for bucket in self._buckets: if bucket is None or", "reinsert key=>values for bucket in oldBuckets: if bucket is None: continue for (key,", "if longest < l: longest = l b = bucket return longest def", "# New max len for buckets self.change_len = self.hash_len / 5 # new", "# Double size of buckets self.hash_len = self.hash_len * 2 # New max", "longest < l: longest = l b = bucket return longest def get_shortest_bucket(self):", "val) if len(bucket) >= self.change_len: # print('growing', 'num buckets: ', len(self._buckets)) self._grow() def", "hash map \"\"\" def __init__(self, hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'),", "# print('growing', 'num buckets: ', len(self._buckets)) self._grow() def _grow(self): # Double size of", "= 0 for bucket in self._buckets: if not bucket: continue n += len(bucket)", "import LinkedList class Hashmap(object): \"\"\" character holding hash map \"\"\" def __init__(self, hash_fn,", "None for bucket in self._buckets: if bucket is None: continue l = len(bucket)", "per bucket self.change_len = length / 5 def _hash(self, key): return self.hash_fn(key) %", "\"\"\" def __init__(self, hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You must", "None: return None self._buckets[pos] = None self.num_values -= 1 return node.val def _shrink(self):", "-= 1 return node.val def _shrink(self): # length = self.hash_len pass def __repr__(self):", "= self._buckets[pos] if bucket is None: return None return bucket.get(key) def delete(self, key):", "# Iterate through all buckets # and reinsert key=>values for bucket in oldBuckets:", "else: bucket.put(key, val) if len(bucket) >= self.change_len: # print('growing', 'num buckets: ', len(self._buckets))", "shortest = 0 b = None for bucket in self._buckets: if bucket is", "l if shortest >= l: shortest = l b = bucket return shortest", "buckets self.hash_len = self.hash_len * 2 # New max len for buckets self.change_len", "None return bucket.get(key) def delete(self, key): \"\"\" Deletes a value in a hashmap", "for (key, val) in bucket: self.put(key, val) def get(self, key): pos = self._hash(key)", "= self.hash_len pass def __repr__(self): return '<Hashmap %r>' % self._buckets def __len__(self): n", "# Max items per bucket self.change_len = length / 5 def _hash(self, key):", "self._buckets: if bucket is None: continue l = len(bucket) if longest < l:", "length / 5 def _hash(self, key): return self.hash_fn(key) % self.hash_len def put(self, key,", "len(self._buckets)) self._grow() def _grow(self): # Double size of buckets self.hash_len = self.hash_len *", "', len(self._buckets)) self._grow() def _grow(self): # Double size of buckets self.hash_len = self.hash_len", "length = self.hash_len pass def __repr__(self): return '<Hashmap %r>' % self._buckets def __len__(self):", "None or len(bucket) == 0: n += 1 return n def get_longest_bucket(self): longest", "is None: continue for (key, val) in bucket: self.put(key, val) def get(self, key):", "self._buckets[pos] if node is None: return None self._buckets[pos] = None self.num_values -= 1", "n def get_longest_bucket(self): longest = 0 b = None for bucket in self._buckets:", "in the map if it exists \"\"\" pos = self._hash(key) node = self._buckets[pos]", "bucket = self._buckets[pos] if bucket is None: self._buckets[pos] = bucket = LinkedList() bucket.put(key,", "None: self._buckets[pos] = bucket = LinkedList() bucket.put(key, val) else: bucket.put(key, val) if len(bucket)", "bucket is None: return None return bucket.get(key) def delete(self, key): \"\"\" Deletes a", "and reinsert key=>values for bucket in oldBuckets: if bucket is None: continue for", "if not bucket: continue n += len(bucket) return n def get_num_empty_buckets(self): n =", "val): pos = self._hash(key) bucket = self._buckets[pos] if bucket is None: self._buckets[pos] =", "hasattr(hash_fn, '__call__'), 'You must provide a hash function' self._buckets = [None] * length", "= l if shortest >= l: shortest = l b = bucket return", "self.change_len = length / 5 def _hash(self, key): return self.hash_fn(key) % self.hash_len def", "None for bucket in self._buckets: if bucket is None: shortest = 0 b", "key, val): pos = self._hash(key) bucket = self._buckets[pos] if bucket is None: self._buckets[pos]", "None self.num_values -= 1 return node.val def _shrink(self): # length = self.hash_len pass", "= self._hash(key) bucket = self._buckets[pos] if bucket is None: self._buckets[pos] = bucket =", "bucket in oldBuckets: if bucket is None: continue for (key, val) in bucket:", "= [None] * length self.hash_len = length self.hash_fn = hash_fn # Max items", "character holding hash map \"\"\" def __init__(self, hash_fn, length=100): self.num_values = 0 assert", "= l b = bucket return longest def get_shortest_bucket(self): shortest = 0 b", "len(bucket) if longest < l: longest = l b = bucket return longest", "is None: self._buckets[pos] = bucket = LinkedList() bucket.put(key, val) else: bucket.put(key, val) if", "holder oldBuckets = self._buckets self._buckets = [None] * self.hash_len # Iterate through all", "function' self._buckets = [None] * length self.hash_len = length self.hash_fn = hash_fn #", "bucket.get(key) def delete(self, key): \"\"\" Deletes a value in a hashmap returns the", "get_longest_bucket(self): longest = 0 b = None for bucket in self._buckets: if bucket", "= 0 assert hasattr(hash_fn, '__call__'), 'You must provide a hash function' self._buckets =", "def get(self, key): pos = self._hash(key) bucket = self._buckets[pos] if bucket is None:", "bucket is None or len(bucket) == 0: n += 1 return n def", "n = 0 for bucket in self._buckets: if bucket is None or len(bucket)", "shortest = l if shortest >= l: shortest = l b = bucket", "a hashmap returns the value in the map if it exists \"\"\" pos", "for bucket in self._buckets: if bucket is None: shortest = 0 b =", "if bucket is None: return None return bucket.get(key) def delete(self, key): \"\"\" Deletes", "= length / 5 def _hash(self, key): return self.hash_fn(key) % self.hash_len def put(self,", "hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You must provide a hash", "put(self, key, val): pos = self._hash(key) bucket = self._buckets[pos] if bucket is None:", "self._buckets: if bucket is None: shortest = 0 b = None break l", "l b = bucket return longest def get_shortest_bucket(self): shortest = 0 b =", "bucket is None: self._buckets[pos] = bucket = LinkedList() bucket.put(key, val) else: bucket.put(key, val)", "self.hash_len / 5 # new bucket holder oldBuckets = self._buckets self._buckets = [None]", "longest def get_shortest_bucket(self): shortest = 0 b = None for bucket in self._buckets:", "if node is None: return None self._buckets[pos] = None self.num_values -= 1 return", "if bucket is None: continue l = len(bucket) if longest < l: longest", "'num buckets: ', len(self._buckets)) self._grow() def _grow(self): # Double size of buckets self.hash_len", ".linkedlist import LinkedList class Hashmap(object): \"\"\" character holding hash map \"\"\" def __init__(self,", "bucket: self.put(key, val) def get(self, key): pos = self._hash(key) bucket = self._buckets[pos] if", "size of buckets self.hash_len = self.hash_len * 2 # New max len for", "def get_shortest_bucket(self): shortest = 0 b = None for bucket in self._buckets: if", "0 b = None for bucket in self._buckets: if bucket is None: shortest", "if shortest == 0: shortest = l if shortest >= l: shortest =", "n += 1 return n def get_longest_bucket(self): longest = 0 b = None", "def _grow(self): # Double size of buckets self.hash_len = self.hash_len * 2 #", ">= self.change_len: # print('growing', 'num buckets: ', len(self._buckets)) self._grow() def _grow(self): # Double", "exists \"\"\" pos = self._hash(key) node = self._buckets[pos] if node is None: return", "the value in the map if it exists \"\"\" pos = self._hash(key) node", "None break l = len(bucket) if shortest == 0: shortest = l if", "bucket in self._buckets: if bucket is None or len(bucket) == 0: n +=", "len for buckets self.change_len = self.hash_len / 5 # new bucket holder oldBuckets", "def put(self, key, val): pos = self._hash(key) bucket = self._buckets[pos] if bucket is", "pos = self._hash(key) bucket = self._buckets[pos] if bucket is None: self._buckets[pos] = bucket", "self._buckets: if not bucket: continue n += len(bucket) return n def get_num_empty_buckets(self): n", "value in a hashmap returns the value in the map if it exists", "hash_fn # Max items per bucket self.change_len = length / 5 def _hash(self,", "n = 0 for bucket in self._buckets: if not bucket: continue n +=", "= self._hash(key) bucket = self._buckets[pos] if bucket is None: return None return bucket.get(key)", "None: continue for (key, val) in bucket: self.put(key, val) def get(self, key): pos", "node is None: return None self._buckets[pos] = None self.num_values -= 1 return node.val", "for bucket in self._buckets: if bucket is None: continue l = len(bucket) if", "must provide a hash function' self._buckets = [None] * length self.hash_len = length", "self.change_len: # print('growing', 'num buckets: ', len(self._buckets)) self._grow() def _grow(self): # Double size", "bucket.put(key, val) else: bucket.put(key, val) if len(bucket) >= self.change_len: # print('growing', 'num buckets:", "< l: longest = l b = bucket return longest def get_shortest_bucket(self): shortest", "pos = self._hash(key) node = self._buckets[pos] if node is None: return None self._buckets[pos]", "return n def get_longest_bucket(self): longest = 0 b = None for bucket in", "b = bucket return longest def get_shortest_bucket(self): shortest = 0 b = None", "def delete(self, key): \"\"\" Deletes a value in a hashmap returns the value", "a value in a hashmap returns the value in the map if it", "/ 5 def _hash(self, key): return self.hash_fn(key) % self.hash_len def put(self, key, val):", "if len(bucket) >= self.change_len: # print('growing', 'num buckets: ', len(self._buckets)) self._grow() def _grow(self):", "Deletes a value in a hashmap returns the value in the map if", "is None: return None self._buckets[pos] = None self.num_values -= 1 return node.val def", "length self.hash_len = length self.hash_fn = hash_fn # Max items per bucket self.change_len", "= hash_fn # Max items per bucket self.change_len = length / 5 def", "__len__(self): n = 0 for bucket in self._buckets: if not bucket: continue n", "return self.hash_fn(key) % self.hash_len def put(self, key, val): pos = self._hash(key) bucket =", "bucket in self._buckets: if bucket is None: shortest = 0 b = None", "continue for (key, val) in bucket: self.put(key, val) def get(self, key): pos =", "holding hash map \"\"\" def __init__(self, hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn,", "length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You must provide a hash function'", "bucket in self._buckets: if not bucket: continue n += len(bucket) return n def", "= len(bucket) if shortest == 0: shortest = l if shortest >= l:", "2 # New max len for buckets self.change_len = self.hash_len / 5 #", "l: longest = l b = bucket return longest def get_shortest_bucket(self): shortest =", "= LinkedList() bucket.put(key, val) else: bucket.put(key, val) if len(bucket) >= self.change_len: # print('growing',", "_hash(self, key): return self.hash_fn(key) % self.hash_len def put(self, key, val): pos = self._hash(key)", "buckets: ', len(self._buckets)) self._grow() def _grow(self): # Double size of buckets self.hash_len =", "* 2 # New max len for buckets self.change_len = self.hash_len / 5", "Iterate through all buckets # and reinsert key=>values for bucket in oldBuckets: if", "buckets # and reinsert key=>values for bucket in oldBuckets: if bucket is None:", "0: shortest = l if shortest >= l: shortest = l b =", "0 b = None for bucket in self._buckets: if bucket is None: continue", "n def get_num_empty_buckets(self): n = 0 for bucket in self._buckets: if bucket is", "items per bucket self.change_len = length / 5 def _hash(self, key): return self.hash_fn(key)", "self.hash_len pass def __repr__(self): return '<Hashmap %r>' % self._buckets def __len__(self): n =", "LinkedList class Hashmap(object): \"\"\" character holding hash map \"\"\" def __init__(self, hash_fn, length=100):", "bucket holder oldBuckets = self._buckets self._buckets = [None] * self.hash_len # Iterate through", "assert hasattr(hash_fn, '__call__'), 'You must provide a hash function' self._buckets = [None] *", "longest = l b = bucket return longest def get_shortest_bucket(self): shortest = 0", "in self._buckets: if bucket is None or len(bucket) == 0: n += 1", "self.put(key, val) def get(self, key): pos = self._hash(key) bucket = self._buckets[pos] if bucket", "self._buckets[pos] = None self.num_values -= 1 return node.val def _shrink(self): # length =", "* self.hash_len # Iterate through all buckets # and reinsert key=>values for bucket", "= self._buckets[pos] if node is None: return None self._buckets[pos] = None self.num_values -=", "'You must provide a hash function' self._buckets = [None] * length self.hash_len =", "+= 1 return n def get_longest_bucket(self): longest = 0 b = None for", "is None or len(bucket) == 0: n += 1 return n def get_longest_bucket(self):", "= None for bucket in self._buckets: if bucket is None: shortest = 0", "class Hashmap(object): \"\"\" character holding hash map \"\"\" def __init__(self, hash_fn, length=100): self.num_values", "val) else: bucket.put(key, val) if len(bucket) >= self.change_len: # print('growing', 'num buckets: ',", "self.hash_len = length self.hash_fn = hash_fn # Max items per bucket self.change_len =", "l = len(bucket) if longest < l: longest = l b = bucket", "return longest def get_shortest_bucket(self): shortest = 0 b = None for bucket in", "= bucket return longest def get_shortest_bucket(self): shortest = 0 b = None for", "self.hash_fn(key) % self.hash_len def put(self, key, val): pos = self._hash(key) bucket = self._buckets[pos]", "None: shortest = 0 b = None break l = len(bucket) if shortest", "return bucket.get(key) def delete(self, key): \"\"\" Deletes a value in a hashmap returns", "= self.hash_len * 2 # New max len for buckets self.change_len = self.hash_len", "is None: return None return bucket.get(key) def delete(self, key): \"\"\" Deletes a value", "n += len(bucket) return n def get_num_empty_buckets(self): n = 0 for bucket in", "/ 5 # new bucket holder oldBuckets = self._buckets self._buckets = [None] *", "1 return node.val def _shrink(self): # length = self.hash_len pass def __repr__(self): return", "or len(bucket) == 0: n += 1 return n def get_longest_bucket(self): longest =", "hash function' self._buckets = [None] * length self.hash_len = length self.hash_fn = hash_fn", "value in the map if it exists \"\"\" pos = self._hash(key) node =", "l = len(bucket) if shortest == 0: shortest = l if shortest >=", "self._buckets = [None] * length self.hash_len = length self.hash_fn = hash_fn # Max", "delete(self, key): \"\"\" Deletes a value in a hashmap returns the value in", "return None return bucket.get(key) def delete(self, key): \"\"\" Deletes a value in a", "self._buckets def __len__(self): n = 0 for bucket in self._buckets: if not bucket:", "if it exists \"\"\" pos = self._hash(key) node = self._buckets[pos] if node is", "node = self._buckets[pos] if node is None: return None self._buckets[pos] = None self.num_values", "# and reinsert key=>values for bucket in oldBuckets: if bucket is None: continue", "% self.hash_len def put(self, key, val): pos = self._hash(key) bucket = self._buckets[pos] if", "= self._buckets[pos] if bucket is None: self._buckets[pos] = bucket = LinkedList() bucket.put(key, val)", "not bucket: continue n += len(bucket) return n def get_num_empty_buckets(self): n = 0", "0 b = None break l = len(bucket) if shortest == 0: shortest", "in self._buckets: if bucket is None: continue l = len(bucket) if longest <", "# new bucket holder oldBuckets = self._buckets self._buckets = [None] * self.hash_len #", "None: return None return bucket.get(key) def delete(self, key): \"\"\" Deletes a value in", "def __repr__(self): return '<Hashmap %r>' % self._buckets def __len__(self): n = 0 for", "bucket in self._buckets: if bucket is None: continue l = len(bucket) if longest", "bucket = self._buckets[pos] if bucket is None: return None return bucket.get(key) def delete(self,", "[None] * self.hash_len # Iterate through all buckets # and reinsert key=>values for", "it exists \"\"\" pos = self._hash(key) node = self._buckets[pos] if node is None:", "bucket is None: continue for (key, val) in bucket: self.put(key, val) def get(self,", "self.num_values -= 1 return node.val def _shrink(self): # length = self.hash_len pass def", "of buckets self.hash_len = self.hash_len * 2 # New max len for buckets", "length self.hash_fn = hash_fn # Max items per bucket self.change_len = length /", "* length self.hash_len = length self.hash_fn = hash_fn # Max items per bucket", "Hashmap(object): \"\"\" character holding hash map \"\"\" def __init__(self, hash_fn, length=100): self.num_values =", "in bucket: self.put(key, val) def get(self, key): pos = self._hash(key) bucket = self._buckets[pos]", "= None self.num_values -= 1 return node.val def _shrink(self): # length = self.hash_len", "== 0: shortest = l if shortest >= l: shortest = l b", "# length = self.hash_len pass def __repr__(self): return '<Hashmap %r>' % self._buckets def", "buckets self.change_len = self.hash_len / 5 # new bucket holder oldBuckets = self._buckets", "from .linkedlist import LinkedList class Hashmap(object): \"\"\" character holding hash map \"\"\" def", "get_shortest_bucket(self): shortest = 0 b = None for bucket in self._buckets: if bucket", "self._hash(key) bucket = self._buckets[pos] if bucket is None: self._buckets[pos] = bucket = LinkedList()", "return None self._buckets[pos] = None self.num_values -= 1 return node.val def _shrink(self): #", "in self._buckets: if not bucket: continue n += len(bucket) return n def get_num_empty_buckets(self):", "len(bucket) return n def get_num_empty_buckets(self): n = 0 for bucket in self._buckets: if", "0 for bucket in self._buckets: if bucket is None or len(bucket) == 0:", "= len(bucket) if longest < l: longest = l b = bucket return", "= self._hash(key) node = self._buckets[pos] if node is None: return None self._buckets[pos] =", "oldBuckets: if bucket is None: continue for (key, val) in bucket: self.put(key, val)", "self._hash(key) node = self._buckets[pos] if node is None: return None self._buckets[pos] = None", "b = None for bucket in self._buckets: if bucket is None: shortest =", "bucket self.change_len = length / 5 def _hash(self, key): return self.hash_fn(key) % self.hash_len", "print('growing', 'num buckets: ', len(self._buckets)) self._grow() def _grow(self): # Double size of buckets", "self._hash(key) bucket = self._buckets[pos] if bucket is None: return None return bucket.get(key) def", "if bucket is None: continue for (key, val) in bucket: self.put(key, val) def", "1 return n def get_longest_bucket(self): longest = 0 b = None for bucket", "def get_longest_bucket(self): longest = 0 b = None for bucket in self._buckets: if", "bucket is None: shortest = 0 b = None break l = len(bucket)", "key): pos = self._hash(key) bucket = self._buckets[pos] if bucket is None: return None", "= 0 b = None for bucket in self._buckets: if bucket is None:", "node.val def _shrink(self): # length = self.hash_len pass def __repr__(self): return '<Hashmap %r>'", "__init__(self, hash_fn, length=100): self.num_values = 0 assert hasattr(hash_fn, '__call__'), 'You must provide a", "bucket is None: continue l = len(bucket) if longest < l: longest =", "0 for bucket in self._buckets: if not bucket: continue n += len(bucket) return", "self._buckets self._buckets = [None] * self.hash_len # Iterate through all buckets # and", "__repr__(self): return '<Hashmap %r>' % self._buckets def __len__(self): n = 0 for bucket", "'__call__'), 'You must provide a hash function' self._buckets = [None] * length self.hash_len", "None: continue l = len(bucket) if longest < l: longest = l b", "longest = 0 b = None for bucket in self._buckets: if bucket is", "b = None break l = len(bucket) if shortest == 0: shortest =", "key): return self.hash_fn(key) % self.hash_len def put(self, key, val): pos = self._hash(key) bucket", "map if it exists \"\"\" pos = self._hash(key) node = self._buckets[pos] if node", "self.hash_len = self.hash_len * 2 # New max len for buckets self.change_len =", "key): \"\"\" Deletes a value in a hashmap returns the value in the", "through all buckets # and reinsert key=>values for bucket in oldBuckets: if bucket", "pass def __repr__(self): return '<Hashmap %r>' % self._buckets def __len__(self): n = 0", "return '<Hashmap %r>' % self._buckets def __len__(self): n = 0 for bucket in", "\"\"\" Deletes a value in a hashmap returns the value in the map", "len(bucket) == 0: n += 1 return n def get_longest_bucket(self): longest = 0", "= 0 for bucket in self._buckets: if bucket is None or len(bucket) ==", "self._grow() def _grow(self): # Double size of buckets self.hash_len = self.hash_len * 2" ]
[ "each non-unit test. Creates and removes a new test table for each test.\"\"\"", "TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context =", "table for each test.\"\"\" # TODO: integrate creating/removing a database from unittest import", "removes a new test table for each test.\"\"\" # TODO: integrate creating/removing a", "flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True", "= True self.app_context = app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all() def", "# from flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing", "unittest import TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa # from", "app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context self.app = app.test_client() with", "each test.\"\"\" # TODO: integrate creating/removing a database from unittest import TestCase from", "= app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all() def tearDown(self): with self.app_context():", "import TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa # from flask.ext.testing", "BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context self.app", "non-unit test. Creates and removes a new test table for each test.\"\"\" #", "class for each non-unit test. Creates and removes a new test table for", "setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context self.app = app.test_client()", "from flask_server_files.sqla_instance import fsa # from flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self):", "test table for each test.\"\"\" # TODO: integrate creating/removing a database from unittest", "for each non-unit test. Creates and removes a new test table for each", "test.\"\"\" # TODO: integrate creating/removing a database from unittest import TestCase from flask_server_files.flask_app", "app.testing = True self.app_context = app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all()", "new test table for each test.\"\"\" # TODO: integrate creating/removing a database from", "app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all() def tearDown(self): with self.app_context(): fsa.session.remove()", "a database from unittest import TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance import", "and removes a new test table for each test.\"\"\" # TODO: integrate creating/removing", "a new test table for each test.\"\"\" # TODO: integrate creating/removing a database", "from flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa # from flask.ext.testing import TestCase", "flask_server_files.sqla_instance import fsa # from flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI']", "# TODO: integrate creating/removing a database from unittest import TestCase from flask_server_files.flask_app import", "database from unittest import TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa", "fsa # from flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test'", "True self.app_context = app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all() def tearDown(self):", "import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context", "from flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing =", "= 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context self.app = app.test_client() with self.app_context():", "Creates and removes a new test table for each test.\"\"\" # TODO: integrate", "flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa # from flask.ext.testing import TestCase class", "integrate creating/removing a database from unittest import TestCase from flask_server_files.flask_app import app from", "TODO: integrate creating/removing a database from unittest import TestCase from flask_server_files.flask_app import app", "app from flask_server_files.sqla_instance import fsa # from flask.ext.testing import TestCase class BaseTest(TestCase): def", "\"\"\"Parent class for each non-unit test. Creates and removes a new test table", "def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context self.app =", "from unittest import TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa #", "'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app)", "creating/removing a database from unittest import TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance", "self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all() def tearDown(self): with self.app_context(): fsa.session.remove() fsa.drop_all()", "test. Creates and removes a new test table for each test.\"\"\" # TODO:", "for each test.\"\"\" # TODO: integrate creating/removing a database from unittest import TestCase", "TestCase from flask_server_files.flask_app import app from flask_server_files.sqla_instance import fsa # from flask.ext.testing import", "class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://tester:tester@localhost:5432/test' app.testing = True self.app_context = app.app_context", "import app from flask_server_files.sqla_instance import fsa # from flask.ext.testing import TestCase class BaseTest(TestCase):", "self.app_context = app.app_context self.app = app.test_client() with self.app_context(): fsa.init_app(app) fsa.create_all() def tearDown(self): with", "import fsa # from flask.ext.testing import TestCase class BaseTest(TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] =" ]
[ "= datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self, name): if", "<reponame>tairan/playground-python<filename>playground/service.py import datetime import pytz from .models import ( Account ) class AccountService():", "def create_new_user(self, name): if not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return act", "= Account(name=name) self.session.add(act) act.commit() return act else: raise Exception('user `{0}` already exist.'.format(name)) def", "raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name = name).first()", "sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user", "class AccountService(): def __init__(self, session): self.session = session def sign_in(self, name): user =", "def __init__(self, session): self.session = session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if", "act.commit() return act else: raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name): account", "act else: raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name", "user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self, name):", "self.session.add(act) act.commit() return act else: raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name):", "datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self, name): if not", "Account(name=name) self.session.add(act) act.commit() return act else: raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self,", "def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise", "session): self.session = session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at", "session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else:", "datetime import pytz from .models import ( Account ) class AccountService(): def __init__(self,", "self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not exist.'.format(name))", ".models import ( Account ) class AccountService(): def __init__(self, session): self.session = session", "create_new_user(self, name): if not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return act else:", "Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name): act =", "if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not exist.'.format(name)) def", "else: raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name =", "= session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC')))", "self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return act else: raise Exception('user `{0}` already", "already exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name = name).first() return account !=", "else: raise Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name):", "import ( Account ) class AccountService(): def __init__(self, session): self.session = session def", "if not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return act else: raise Exception('user", "exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name = name).first() return account != null", "user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does", "act = Account(name=name) self.session.add(act) act.commit() return act else: raise Exception('user `{0}` already exist.'.format(name))", "not exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit()", "return act else: raise Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name): account =", "`{0}` already exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name = name).first() return account", "( Account ) class AccountService(): def __init__(self, session): self.session = session def sign_in(self,", "raise Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name): act", ") class AccountService(): def __init__(self, session): self.session = session def sign_in(self, name): user", "import datetime import pytz from .models import ( Account ) class AccountService(): def", "= self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not", "name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}`", "exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return", "`{0}` does not exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name): act = Account(name=name)", "Exception('user `{0}` already exist.'.format(name)) def user_exists(self, name): account = self.session.query(Account).filter_by(name = name).first() return", "pytz from .models import ( Account ) class AccountService(): def __init__(self, session): self.session", "__init__(self, session): self.session = session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user:", "self.session = session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt() if user: user.last_signed_at =", "name): if not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return act else: raise", "user: user.last_signed_at = datetime.datetime.now(datetime.datetime.now(tz=pytz.timezone('UTC'))) else: raise Exception('user `{0}` does not exist.'.format(name)) def create_new_user(self,", "does not exist.'.format(name)) def create_new_user(self, name): if not self.user_exists(name): act = Account(name=name) self.session.add(act)", "from .models import ( Account ) class AccountService(): def __init__(self, session): self.session =", "AccountService(): def __init__(self, session): self.session = session def sign_in(self, name): user = self.session.Query(Account).filter(name=name).fisrt()", "Account ) class AccountService(): def __init__(self, session): self.session = session def sign_in(self, name):", "import pytz from .models import ( Account ) class AccountService(): def __init__(self, session):", "not self.user_exists(name): act = Account(name=name) self.session.add(act) act.commit() return act else: raise Exception('user `{0}`" ]
[ "ne seront pas ' 'visibles par les autres adhérents.', ) id_file = models.FileField(", "False self.is_president = True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the user as", "null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical", "max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, )", "ou licence', upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result", "class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='',", "\"Informations personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify", "self.is_member = True self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive", "PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result = \"Informations personnelles pour \" +", "default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False,", "adhérent(e)\" ) objects = RoleManager() def set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with", "Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', )", "the user as secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = True self.is_treasurer", "( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain", "default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer =", ") is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" )", "False self.is_president = False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the user as", "on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette case", ") id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField(", "is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president", "treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = True self.is_president", "self.is_president = False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\"", "is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" )", "= False self.is_inactive = False def set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with", "def set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary", "the user as treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer", "= models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" )", "pour \" + \\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\"", "import models, transaction from teamspirit.core.models import Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager,", "models related to the app ``profiles``.\"\"\" from django.db import models, transaction from teamspirit.core.models", "blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical ou", "rename_medical_file, ) from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number =", ") is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\"", "False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic():", "autres adhérents.', ) id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file", "personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address =", "default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager()", "models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False,", "with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = True self.is_president =", "the user as member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary = False self.is_treasurer", "verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def set_as_member(self): \"\"\"Qualify the user as member.\"\"\"", "president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president", "default=False, verbose_name='Profil privé ?', help_text='Si cette case est cochée, mes informations ne seront", "= models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def set_as_member(self): \"\"\"Qualify the", "= False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with", "\"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False", "RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\"", "self.is_secretary = False self.is_treasurer = True self.is_president = False self.is_inactive = False def", "Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary", "upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result = \"Informations", "verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence',", "user = User.objects.get(personal=self.id) result = \"Informations personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\"", "\"\"\"Qualify the user as member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary = False", "= False self.is_secretary = True self.is_treasurer = False self.is_president = False self.is_inactive =", "\"\"\"Qualify the user as president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False", "False self.is_treasurer = False self.is_president = True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify", "self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic(): self.is_member", "null=True, blank=False, default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile =", "= models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive =", "set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary =", "= models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE,", "member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary = False self.is_treasurer = False self.is_president", "is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\"", "verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def", "upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, )", "verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non", "from django.db import models, transaction from teamspirit.core.models import Address from teamspirit.profiles.managers import (", "= models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette case est cochée, mes informations", "= False def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic(): self.is_member =", "\\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField(", "= False self.is_treasurer = False self.is_president = False self.is_inactive = False def set_as_secretary(self):", "with transaction.atomic(): self.is_member = True self.is_secretary = False self.is_treasurer = False self.is_president =", "self.is_secretary = True self.is_treasurer = False self.is_president = False self.is_inactive = False def", "def __str__(self): user = User.objects.get(personal=self.id) result = \"Informations personnelles pour \" + \\", "True self.is_president = False self.is_inactive = False def set_as_president(self): \"\"\"Qualify the user as", "result = \"Informations personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\" return result class", "self.is_president = False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\"", "self.is_inactive = False def set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with transaction.atomic(): self.is_member", "as member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary = False self.is_treasurer = False", "objects = RoleManager() def set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with transaction.atomic(): self.is_member", "= False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with", "= True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with", "RoleManager() def set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with transaction.atomic(): self.is_member = True", "user as inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer =", "pas ' 'visibles par les autres adhérents.', ) id_file = models.FileField( null=True, blank=True,", "with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president =", "set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary =", "User.objects.get(personal=self.id) result = \"Informations personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\" return result", "<gh_stars>0 \"\"\"Contain the models related to the app ``profiles``.\"\"\" from django.db import models,", "default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False,", "import Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models", "verbose_name='Profil privé ?', help_text='Si cette case est cochée, mes informations ne seront pas", "= models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True,", "phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address = models.ForeignKey( to=Address,", "True self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive = False", "default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def set_as_member(self): \"\"\"Qualify the user as", "= False self.is_president = False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the user", "par les autres adhérents.', ) id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file,", "the user as president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer", "to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette", "cochée, mes informations ne seront pas ' 'visibles par les autres adhérents.', )", "address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé", ") medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects", "privé ?', help_text='Si cette case est cochée, mes informations ne seront pas '", ") has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette case est cochée,", "False self.is_president = False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the user as", "= False def set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with transaction.atomic(): self.is_member =", "user as president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer =", "self.is_secretary = False self.is_treasurer = False self.is_president = True self.is_inactive = False def", "models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si", ") objects = PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result = \"Informations personnelles", "self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive", "with transaction.atomic(): self.is_member = False self.is_secretary = True self.is_treasurer = False self.is_president =", ") is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" )", "def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary", "= False self.is_treasurer = False self.is_president = True self.is_inactive = False def set_as_inactive(self):", "self.is_member = False self.is_secretary = False self.is_treasurer = True self.is_president = False self.is_inactive", "False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic():", "verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField(", "False def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic(): self.is_member = False", "models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette case est cochée, mes informations ne", "self.is_member = False self.is_secretary = True self.is_treasurer = False self.is_president = False self.is_inactive", "self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president = True self.is_inactive", "= User.objects.get(personal=self.id) result = \"Informations personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\" return", "import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import User class Personal(models.Model):", "False self.is_secretary = False self.is_treasurer = False self.is_president = True self.is_inactive = False", "from teamspirit.core.models import Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, )", "has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette case est cochée, mes", "teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone',", "id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True,", "self.is_treasurer = False self.is_president = False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the", "= True self.is_president = False self.is_inactive = False def set_as_president(self): \"\"\"Qualify the user", "transaction.atomic(): self.is_member = False self.is_secretary = True self.is_treasurer = False self.is_president = False", "transaction from teamspirit.core.models import Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file,", "\"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary =", "self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic(): self.is_member", "False self.is_treasurer = False self.is_president = False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify", "False def set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with transaction.atomic(): self.is_member = False", "\"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False", "False self.is_secretary = True self.is_treasurer = False self.is_president = False self.is_inactive = False", "'visibles par les autres adhérents.', ) id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité',", "objects = PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result = \"Informations personnelles pour", "d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file,", "+ \\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member =", "self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive = False def", "set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary =", "self.is_treasurer = False self.is_president = True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the", "= False def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic(): self.is_member =", "is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def set_as_member(self): \"\"\"Qualify", "\" + \\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member", "False def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic(): self.is_member = False", "seront pas ' 'visibles par les autres adhérents.', ) id_file = models.FileField( null=True,", "verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self): user =", "personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's", "``profiles``.\"\"\" from django.db import models, transaction from teamspirit.core.models import Address from teamspirit.profiles.managers import", "= RoleManager() def set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with transaction.atomic(): self.is_member =", "?', help_text='Si cette case est cochée, mes informations ne seront pas ' 'visibles", "user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField(", "models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer", "transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president = True", "l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\"", "the app ``profiles``.\"\"\" from django.db import models, transaction from teamspirit.core.models import Address from", "models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def set_as_member(self): \"\"\"Qualify the user", "= False self.is_treasurer = True self.is_president = False self.is_inactive = False def set_as_president(self):", "django.db import models, transaction from teamspirit.core.models import Address from teamspirit.profiles.managers import ( PersonalManager,", "= False self.is_secretary = False self.is_treasurer = True self.is_president = False self.is_inactive =", "False self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive = True", "{user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e)", "= True self.is_treasurer = False self.is_president = False self.is_inactive = False def set_as_treasurer(self):", "\"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = True", "\"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address", "licence', upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result =", "= False def set_as_secretary(self): \"\"\"Qualify the user as secretary.\"\"\" with transaction.atomic(): self.is_member =", "\"\"\"Contain the models related to the app ``profiles``.\"\"\" from django.db import models, transaction", "to the app ``profiles``.\"\"\" from django.db import models, transaction from teamspirit.core.models import Address", "rename_id_file, rename_medical_file, ) from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number", ") address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil", "True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic():", "as inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False", "teamspirit.core.models import Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from", "User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False,", "' 'visibles par les autres adhérents.', ) id_file = models.FileField( null=True, blank=True, verbose_name='Pièce", "models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat", "= False self.is_secretary = False self.is_treasurer = False self.is_president = True self.is_inactive =", "as secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = True self.is_treasurer = False", "PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal", "verbose_name='Téléphone', null=True, blank=False, default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile", "models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField(", "result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\"", "role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" ) is_secretary = models.BooleanField( default=False,", "informations ne seront pas ' 'visibles par les autres adhérents.', ) id_file =", "related to the app ``profiles``.\"\"\" from django.db import models, transaction from teamspirit.core.models import", "from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import User", "mes informations ne seront pas ' 'visibles par les autres adhérents.', ) id_file", "medical_file = models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects =", "secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = True self.is_treasurer = False self.is_president", "teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import User class", "= PersonalManager() def __str__(self): user = User.objects.get(personal=self.id) result = \"Informations personnelles pour \"", "Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file, rename_medical_file, ) from teamspirit.users.models import", "médical ou licence', upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self): user = User.objects.get(personal=self.id)", "help_text='Si cette case est cochée, mes informations ne seront pas ' 'visibles par", "class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de l'association\" )", "self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic(): self.is_member", "False def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic(): self.is_member = False", "null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?', help_text='Si cette case est", "verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\"", "is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive", "= False self.is_president = True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the user", "the user as inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer", "inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president", "cette case est cochée, mes informations ne seront pas ' 'visibles par les", "= models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president =", "= models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects", "the models related to the app ``profiles``.\"\"\" from django.db import models, transaction from", "as treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = True", "= \"Informations personnelles pour \" + \\ f\"{user.first_name} {user.last_name}\" return result class Role(models.Model):", "= False self.is_president = False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the user", ") objects = RoleManager() def set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with transaction.atomic():", "case est cochée, mes informations ne seront pas ' 'visibles par les autres", "adhérents.', ) id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, ) medical_file =", "self.is_treasurer = True self.is_president = False self.is_inactive = False def set_as_president(self): \"\"\"Qualify the", "user as member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary = False self.is_treasurer =", "False self.is_inactive = False def set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with transaction.atomic():", "models, transaction from teamspirit.core.models import Address from teamspirit.profiles.managers import ( PersonalManager, RoleManager, rename_id_file,", "import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True,", "models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects =", "models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects = PersonalManager() def", "self.is_president = False self.is_inactive = False def set_as_president(self): \"\"\"Qualify the user as president.\"\"\"", "default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField( default=False, verbose_name=\"Présidence\" ) is_inactive = models.BooleanField( default=False,", "set_as_president(self): \"\"\"Qualify the user as president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary =", "from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField( max_length=20,", "def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary", "est cochée, mes informations ne seront pas ' 'visibles par les autres adhérents.',", "= models.FileField( null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects = PersonalManager()", "self.is_president = True self.is_inactive = False def set_as_inactive(self): \"\"\"Qualify the user as inactive.\"\"\"", "transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False self.is_president = False", "de l'association\" ) is_secretary = models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False,", "__str__(self): user = User.objects.get(personal=self.id) result = \"Informations personnelles pour \" + \\ f\"{user.first_name}", "def set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary", "app ``profiles``.\"\"\" from django.db import models, transaction from teamspirit.core.models import Address from teamspirit.profiles.managers", "user as secretary.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = True self.is_treasurer =", "= False self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive =", "information.\"\"\" phone_number = models.CharField( max_length=20, verbose_name='Téléphone', null=True, blank=False, default='', ) address = models.ForeignKey(", "blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self): user", "= True self.is_secretary = False self.is_treasurer = False self.is_president = False self.is_inactive =", "def set_as_treasurer(self): \"\"\"Qualify the user as treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary", ") is_inactive = models.BooleanField( default=False, verbose_name=\"Non adhérent(e)\" ) objects = RoleManager() def set_as_member(self):", "True self.is_treasurer = False self.is_president = False self.is_inactive = False def set_as_treasurer(self): \"\"\"Qualify", "models.BooleanField( default=False, verbose_name=\"Secrétariat\" ) is_treasurer = models.BooleanField( default=False, verbose_name=\"Trésorerie\" ) is_president = models.BooleanField(", "as president.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = False", "= models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField( default=False, verbose_name='Profil privé ?',", "self.is_treasurer = False self.is_president = False self.is_inactive = False def set_as_secretary(self): \"\"\"Qualify the", "transaction.atomic(): self.is_member = True self.is_secretary = False self.is_treasurer = False self.is_president = False", "return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True, verbose_name=\"Adhérent(e) de", "set_as_member(self): \"\"\"Qualify the user as member.\"\"\" with transaction.atomic(): self.is_member = True self.is_secretary =", "transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer = True self.is_president = False", "False self.is_treasurer = True self.is_president = False self.is_inactive = False def set_as_president(self): \"\"\"Qualify", "False self.is_secretary = False self.is_treasurer = True self.is_president = False self.is_inactive = False", "les autres adhérents.', ) id_file = models.FileField( null=True, blank=True, verbose_name='Pièce d\\'identité', upload_to=rename_id_file, )", "blank=False, default='', ) address = models.ForeignKey( to=Address, on_delete=models.CASCADE, null=False, ) has_private_profile = models.BooleanField(", "null=True, blank=True, verbose_name='Certificat médical ou licence', upload_to=rename_medical_file, ) objects = PersonalManager() def __str__(self):", ") from teamspirit.users.models import User class Personal(models.Model): \"\"\"Contain personal information.\"\"\" phone_number = models.CharField(", "user as treasurer.\"\"\" with transaction.atomic(): self.is_member = False self.is_secretary = False self.is_treasurer =", "f\"{user.first_name} {user.last_name}\" return result class Role(models.Model): \"\"\"Qualify user's role.\"\"\" is_member = models.BooleanField( default=True," ]
[ "from client.client_request import client_request @click.command() @click.argument('http_verb') @click.argument('url') def httlemon(http_verb, url): beautified_response = client_request(http_verb,", "click from client.client_request import client_request @click.command() @click.argument('http_verb') @click.argument('url') def httlemon(http_verb, url): beautified_response =", "import click from client.client_request import client_request @click.command() @click.argument('http_verb') @click.argument('url') def httlemon(http_verb, url): beautified_response", "import client_request @click.command() @click.argument('http_verb') @click.argument('url') def httlemon(http_verb, url): beautified_response = client_request(http_verb, url) click.echo(beautified_response)", "<gh_stars>1-10 import click from client.client_request import client_request @click.command() @click.argument('http_verb') @click.argument('url') def httlemon(http_verb, url):", "client.client_request import client_request @click.command() @click.argument('http_verb') @click.argument('url') def httlemon(http_verb, url): beautified_response = client_request(http_verb, url)" ]
[ "def display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text) if ( text_lines", "def setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor):", "else f'full result, {len(rows)} row(s)' ) ) def get_text_size(text): lines = text.split('\\n') column_count", "exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as", "or not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return query + f' LIMIT", "= os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as f: return json.load(f) except", "> MAX_ROWS else f'full result, {len(rows)} row(s)' ) ) def get_text_size(text): lines =", "metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor): headers = [col[0] for col in", "get_terminal_size() text_columns, text_lines = get_text_size(text) if ( text_lines + 2 <= term_lines and", "omit for ' 'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor): headers", "print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please set up {filename} as follows:", "def run(): args = parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query:", "HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try:", "rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing '", "cursor = connection.cursor() if args.query: query = sys.stdin.read() if args.query == '-' else", "readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running", "') if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args", "while True: query = input('> ') if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt):", "query = input('> ') if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!')", "sys import json import atexit from argparse import ArgumentParser from shutil import get_terminal_size", "json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please set up", "set up {filename} as follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\":", ") return parser.parse_args() def render(cursor): headers = [col[0] for col in cursor.description] rows", "( text_lines + 2 <= term_lines and text_columns <= term_columns ) or not", "+ ( f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS else f'full result, {len(rows)}", "read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as f: return", "text_lines + 2 <= term_lines and text_columns <= term_columns ) or not sys.stdout.isatty():", "raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr)", "file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file,", "to run, use - to read from stdin or omit for ' 'interactive", "term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text) if ( text_lines + 2 <=", "os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename)", "stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns, term_lines = get_terminal_size() text_columns,", "return query + f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage", "with open(filename) as f: return json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print(", "exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr) return", "nargs='?', ) return parser.parse_args() def render(cursor): headers = [col[0] for col in cursor.description]", "), file=sys.stderr, ) sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query to", "True: query = input('> ') if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print()", "<= term_lines and text_columns <= term_columns ) or not sys.stdout.isatty(): return print(text) page(text)", "ahead and type some SQL...') try: while True: query = input('> ') if", "some SQL...') try: while True: query = input('> ') if query: run_query(cursor, query)", "+ f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception:", "from textwrap import dedent from pkg_resources import get_distribution from databricks_dbapi import databricks from", "print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass", "print('Bye!') def run(): args = parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if", "connection.cursor() if args.query: query = sys.stdin.read() if args.query == '-' else args.query run_query(cursor,", "= text.split('\\n') column_count = max(map(len, lines)) line_count = len(lines) return column_count, line_count def", "table = tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing ' + ( f'first", "TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument( 'query',", "= ArgumentParser() parser.add_argument( 'query', help='query to run, use - to read from stdin", "+ 2 <= term_lines and text_columns <= term_columns ) or not sys.stdout.isatty(): return", "except Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline try:", "try: return exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except", "f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS else f'full result, {len(rows)} row(s)' )", "run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args = parse_args() connection", "KeyboardInterrupt): print() print('Bye!') def run(): args = parse_args() connection = databricks.connect(**read_credentials()) cursor =", "API ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def parse_args(): parser = ArgumentParser()", "\"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def", "Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns, term_lines =", "databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query = sys.stdin.read() if args.query == '-'", "= cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing ' +", "( table + '\\n\\nshowing ' + ( f'first {MAX_ROWS} rows' if len(rows) >", "display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text) if ( text_lines +", "os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as f: return json.load(f) except FileNotFoundError:", "go ahead and type some SQL...') try: while True: query = input('> ')", ") sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query to run, use", "setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go ahead and type some SQL...') try:", "print() print('Bye!') def run(): args = parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor()", "line_count def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass", "import os import sys import json import atexit from argparse import ArgumentParser from", "'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor): headers = [col[0] for", "= [col[0] for col in cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers)", "= get_text_size(text) if ( text_lines + 2 <= term_lines and text_columns <= term_columns", "except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode,", "Please set up {filename} as follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\",", "tabulate import tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename", "as follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS", "dedent from pkg_resources import get_distribution from databricks_dbapi import databricks from tabulate import tabulate", "file=sys.stderr, ) sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query to run,", "except Exception: raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as e:", "run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def", "Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY)", "return parser.parse_args() def render(cursor): headers = [col[0] for col in cursor.description] rows =", "len(lines) return column_count, line_count def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\"))", "filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as f: return json.load(f)", "headers = [col[0] for col in cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS],", "len(rows) > MAX_ROWS else f'full result, {len(rows)} row(s)' ) ) def get_text_size(text): lines", "try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import", "def parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query to run, use - to", "column_count, line_count def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError:", "json import atexit from argparse import ArgumentParser from shutil import get_terminal_size from subprocess", "parser.add_argument( 'query', help='query to run, use - to read from stdin or omit", "parser.parse_args() def render(cursor): headers = [col[0] for col in cursor.description] rows = cursor.fetchall()", "table + '\\n\\nshowing ' + ( f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS", "process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns,", "ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument(", "= get_terminal_size() text_columns, text_lines = get_text_size(text) if ( text_lines + 2 <= term_lines", "sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return query + f' LIMIT {MAX_ROWS +", "try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query))", "100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' )", "except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please set up {filename}", "if len(rows) > MAX_ROWS else f'full result, {len(rows)} row(s)' ) ) def get_text_size(text):", "f'''\\ Please set up {filename} as follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\":", "f'full result, {len(rows)} row(s)' ) ) def get_text_size(text): lines = text.split('\\n') column_count =", "get_distribution from databricks_dbapi import databricks from tabulate import tabulate MAX_ROWS = 100 HISTORY", "setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline()", "FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go", "= databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query = sys.stdin.read() if args.query ==", "text_lines = get_text_size(text) if ( text_lines + 2 <= term_lines and text_columns <=", "def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor))", "import ArgumentParser from shutil import get_terminal_size from subprocess import Popen, PIPE from textwrap", "ArgumentParser() parser.add_argument( 'query', help='query to run, use - to read from stdin or", "read from stdin or omit for ' 'interactive session', metavar='QUERY', nargs='?', ) return", "lines)) line_count = len(lines) return column_count, line_count def page(output): process = Popen([\"less\", \"-R\"],", "\"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}''' ),", "row(s)' ) ) def get_text_size(text): lines = text.split('\\n') column_count = max(map(len, lines)) line_count", "display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def", "result, {len(rows)} row(s)' ) ) def get_text_size(text): lines = text.split('\\n') column_count = max(map(len,", "as f: return json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\", "def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go ahead and type some", "if args.query: query = sys.stdin.read() if args.query == '-' else args.query run_query(cursor, query)", "os import sys import json import atexit from argparse import ArgumentParser from shutil", "def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def", "= connection.cursor() if args.query: query = sys.stdin.read() if args.query == '-' else args.query", "NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1)", "term_columns ) or not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return query +", "'.databricks-credentials.json' ) try: with open(filename) as f: return json.load(f) except FileNotFoundError: print('Databricks credentials", "try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines", ") or not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return query + f'", "term_lines and text_columns <= term_columns ) or not sys.stdout.isatty(): return print(text) page(text) def", "return exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception", "try: while True: query = input('> ') if query: run_query(cursor, query) except (EOFError,", "'\\n\\nshowing ' + ( f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS else f'full", "ArgumentParser from shutil import get_terminal_size from subprocess import Popen, PIPE from textwrap import", "lines = text.split('\\n') column_count = max(map(len, lines)) line_count = len(lines) return column_count, line_count", "query + f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except", "use - to read from stdin or omit for ' 'interactive session', metavar='QUERY',", "parser = ArgumentParser() parser.add_argument( 'query', help='query to run, use - to read from", "}}''' ), file=sys.stderr, ) sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query", "run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go ahead and type some SQL...')", "+ '\\n\\nshowing ' + ( f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS else", "CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr, )", "return column_count, line_count def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except", "up {filename} as follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR", "import sys import json import atexit from argparse import ArgumentParser from shutil import", "headers) return ( table + '\\n\\nshowing ' + ( f'first {MAX_ROWS} rows' if", "term_columns, term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text) if ( text_lines + 2", "Exception: raise exception def run_query(cursor, query): try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e),", "= Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns, term_lines", ") def get_text_size(text): lines = text.split('\\n') column_count = max(map(len, lines)) line_count = len(lines)", "open(filename) as f: return json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent(", "try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in", "cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline", "mode, go ahead and type some SQL...') try: while True: query = input('>", "and type some SQL...') try: while True: query = input('> ') if query:", "= os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with", "+ 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor,", "\"token\": \"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def parse_args(): parser", "return ( table + '\\n\\nshowing ' + ( f'first {MAX_ROWS} rows' if len(rows)", "print('running in interactive mode, go ahead and type some SQL...') try: while True:", "tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing ' + ( f'first {MAX_ROWS} rows'", "text_columns, text_lines = get_text_size(text) if ( text_lines + 2 <= term_lines and text_columns", "\"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr,", "= parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query = sys.stdin.read()", "dedent( f'''\\ Please set up {filename} as follows: {{ \"cluster\": \"A CLUSTER NAME\",", "def render(cursor): headers = [col[0] for col in cursor.description] rows = cursor.fetchall() table", "'.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as", "cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing ' + (", "in interactive mode, go ahead and type some SQL...') try: while True: query", "text_columns <= term_columns ) or not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return", "connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query = sys.stdin.read() if args.query", "def get_text_size(text): lines = text.split('\\n') column_count = max(map(len, lines)) line_count = len(lines) return", "import atexit from argparse import ArgumentParser from shutil import get_terminal_size from subprocess import", "session', metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor): headers = [col[0] for col", "from tabulate import tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials():", "page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text):", "process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines =", "\"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def parse_args(): parser =", "from shutil import get_terminal_size from subprocess import Popen, PIPE from textwrap import dedent", "= len(lines) return column_count, line_count def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE) try:", "not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return query + f' LIMIT {MAX_ROWS", "query = sys.stdin.read() if args.query == '-' else args.query run_query(cursor, query) else: run_interactive(cursor)", "except IOError: pass def display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text)", "MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'),", "(EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args = parse_args() connection = databricks.connect(**read_credentials()) cursor", "import Popen, PIPE from textwrap import dedent from pkg_resources import get_distribution from databricks_dbapi", "<= term_columns ) or not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query): return query", "interactive mode, go ahead and type some SQL...') try: while True: query =", "run(): args = parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query", "in cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return ( table +", "atexit from argparse import ArgumentParser from shutil import get_terminal_size from subprocess import Popen,", "{{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}'''", "page(text) def sanitize_query(query): return query + f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception):", "tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join(", "IOError: pass def display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text) if", "text.split('\\n') column_count = max(map(len, lines)) line_count = len(lines) return column_count, line_count def page(output):", "print(text) page(text) def sanitize_query(query): return query + f' LIMIT {MAX_ROWS + 1}' def", "return print(text) page(text) def sanitize_query(query): return query + f' LIMIT {MAX_ROWS + 1}'", "sys.exit(1) def parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query to run, use -", "e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError:", "1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor, query):", "{MAX_ROWS + 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise exception def", "databricks_dbapi import databricks from tabulate import tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'),", "LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise exception", "from subprocess import Popen, PIPE from textwrap import dedent from pkg_resources import get_distribution", "- to read from stdin or omit for ' 'interactive session', metavar='QUERY', nargs='?',", "print( dedent( f'''\\ Please set up {filename} as follows: {{ \"cluster\": \"A CLUSTER", "render(cursor): headers = [col[0] for col in cursor.description] rows = cursor.fetchall() table =", "import get_terminal_size from subprocess import Popen, PIPE from textwrap import dedent from pkg_resources", "SQL...') try: while True: query = input('> ') if query: run_query(cursor, query) except", "if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args =", "for ' 'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor): headers =", "import dedent from pkg_resources import get_distribution from databricks_dbapi import databricks from tabulate import", "f: return json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please", "import databricks from tabulate import tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history')", "[col[0] for col in cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return", "cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing", "{MAX_ROWS} rows' if len(rows) > MAX_ROWS else f'full result, {len(rows)} row(s)' ) )", "for col in cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return (", "{filename} as follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API", "Popen, PIPE from textwrap import dedent from pkg_resources import get_distribution from databricks_dbapi import", "try: with open(filename) as f: return json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr)", "or omit for ' 'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor):", "parse_args(): parser = ArgumentParser() parser.add_argument( 'query', help='query to run, use - to read", "credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please set up {filename} as follows: {{", "from databricks_dbapi import databricks from tabulate import tabulate MAX_ROWS = 100 HISTORY =", "def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as f:", "FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please set up {filename} as", "col in cursor.description] rows = cursor.fetchall() table = tabulate(rows[:MAX_ROWS], headers) return ( table", "line_count = len(lines) return column_count, line_count def page(output): process = Popen([\"less\", \"-R\"], stdin=PIPE)", "pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go ahead", "if ( text_lines + 2 <= term_lines and text_columns <= term_columns ) or", "type some SQL...') try: while True: query = input('> ') if query: run_query(cursor,", "= input('> ') if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def", "subprocess import Popen, PIPE from textwrap import dedent from pkg_resources import get_distribution from", "stdin or omit for ' 'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args() def", "( f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS else f'full result, {len(rows)} row(s)'", "get_text_size(text): lines = text.split('\\n') column_count = max(map(len, lines)) line_count = len(lines) return column_count,", "parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query = sys.stdin.read() if", "rows' if len(rows) > MAX_ROWS else f'full result, {len(rows)} row(s)' ) ) def", "run, use - to read from stdin or omit for ' 'interactive session',", "to read from stdin or omit for ' 'interactive session', metavar='QUERY', nargs='?', )", "max(map(len, lines)) line_count = len(lines) return column_count, line_count def page(output): process = Popen([\"less\",", "os.path.expanduser('~'), '.databricks-credentials.json' ) try: with open(filename) as f: return json.load(f) except FileNotFoundError: print('Databricks", "column_count = max(map(len, lines)) line_count = len(lines) return column_count, line_count def page(output): process", "return display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY)", "f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise", "pass def display(text): term_columns, term_lines = get_terminal_size() text_columns, text_lines = get_text_size(text) if (", "print(get_distribution('dbq')) print('running in interactive mode, go ahead and type some SQL...') try: while", "input('> ') if query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def run():", "'query', help='query to run, use - to read from stdin or omit for", "import json import atexit from argparse import ArgumentParser from shutil import get_terminal_size from", "query): try: cursor.execute(sanitize_query(query)) except Exception as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline():", "' + ( f'first {MAX_ROWS} rows' if len(rows) > MAX_ROWS else f'full result,", "follows: {{ \"cluster\": \"A CLUSTER NAME\", \"host\": \"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\"", "import get_distribution from databricks_dbapi import databricks from tabulate import tabulate MAX_ROWS = 100", "readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive", "query: run_query(cursor, query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args = parse_args()", "argparse import ArgumentParser from shutil import get_terminal_size from subprocess import Popen, PIPE from", "from argparse import ArgumentParser from shutil import get_terminal_size from subprocess import Popen, PIPE", "from pkg_resources import get_distribution from databricks_dbapi import databricks from tabulate import tabulate MAX_ROWS", "return json.load(f) except FileNotFoundError: print('Databricks credentials missing!', file=sys.stderr) print( dedent( f'''\\ Please set", "args = parse_args() connection = databricks.connect(**read_credentials()) cursor = connection.cursor() if args.query: query =", "and text_columns <= term_columns ) or not sys.stdout.isatty(): return print(text) page(text) def sanitize_query(query):", "databricks from tabulate import tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def", "\"dbc-????????-????.cloud.databricks.com\", \"token\": \"YOUR API ACCESS TOKEN\" }}''' ), file=sys.stderr, ) sys.exit(1) def parse_args():", ") ) def get_text_size(text): lines = text.split('\\n') column_count = max(map(len, lines)) line_count =", "missing!', file=sys.stderr) print( dedent( f'''\\ Please set up {filename} as follows: {{ \"cluster\":", "= tabulate(rows[:MAX_ROWS], headers) return ( table + '\\n\\nshowing ' + ( f'first {MAX_ROWS}", ") try: with open(filename) as f: return json.load(f) except FileNotFoundError: print('Databricks credentials missing!',", "query) except (EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args = parse_args() connection =", "def sanitize_query(query): return query + f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try:", "= max(map(len, lines)) line_count = len(lines) return column_count, line_count def page(output): process =", "as e: print(try_extract_error(e), file=sys.stderr) return display(render(cursor)) def setup_readline(): import readline try: readline.read_history_file(HISTORY) except", "get_text_size(text) if ( text_lines + 2 <= term_lines and text_columns <= term_columns )", "pkg_resources import get_distribution from databricks_dbapi import databricks from tabulate import tabulate MAX_ROWS =", "PIPE from textwrap import dedent from pkg_resources import get_distribution from databricks_dbapi import databricks", "{len(rows)} row(s)' ) ) def get_text_size(text): lines = text.split('\\n') column_count = max(map(len, lines))", "sanitize_query(query): return query + f' LIMIT {MAX_ROWS + 1}' def try_extract_error(exception): try: return", "HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go ahead and type", "' 'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args() def render(cursor): headers = [col[0]", "def try_extract_error(exception): try: return exception.args[0].status.errorMessage except Exception: raise exception def run_query(cursor, query): try:", "from stdin or omit for ' 'interactive session', metavar='QUERY', nargs='?', ) return parser.parse_args()", "textwrap import dedent from pkg_resources import get_distribution from databricks_dbapi import databricks from tabulate", "shutil import get_terminal_size from subprocess import Popen, PIPE from textwrap import dedent from", "= 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename = os.path.join( os.path.expanduser('~'), '.databricks-credentials.json'", "MAX_ROWS else f'full result, {len(rows)} row(s)' ) ) def get_text_size(text): lines = text.split('\\n')", "import readline try: readline.read_history_file(HISTORY) except FileNotFoundError: pass atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq'))", "atexit.register(readline.write_history_file, HISTORY) def run_interactive(cursor): setup_readline() print(get_distribution('dbq')) print('running in interactive mode, go ahead and", "file=sys.stderr) print( dedent( f'''\\ Please set up {filename} as follows: {{ \"cluster\": \"A", "except (EOFError, KeyboardInterrupt): print() print('Bye!') def run(): args = parse_args() connection = databricks.connect(**read_credentials())", "import tabulate MAX_ROWS = 100 HISTORY = os.path.join(os.path.expanduser('~'), '.dbq_history') def read_credentials(): filename =", "args.query: query = sys.stdin.read() if args.query == '-' else args.query run_query(cursor, query) else:", "\"-R\"], stdin=PIPE) try: process.communicate(output.encode(\"utf-8\")) except IOError: pass def display(text): term_columns, term_lines = get_terminal_size()", "get_terminal_size from subprocess import Popen, PIPE from textwrap import dedent from pkg_resources import", "help='query to run, use - to read from stdin or omit for '", "2 <= term_lines and text_columns <= term_columns ) or not sys.stdout.isatty(): return print(text)" ]
[ "# - if input is a list ( and not a dict/ class", "Possible optimizations # - if input is a list ( and not a", ": Marshmallow schemas : Possible optimizations # - if input is a list", "# TODO : Marshmallow schemas : Possible optimizations # - if input is", "it, zipped with declared fields. # - from an existing schema, have a", "TODO : Marshmallow schemas : Possible optimizations # - if input is a", "way to \"restrict\" the field to a \"smaller\" field. # A kind fo", "the field to a \"smaller\" field. # A kind fo gradual typing i", "( and not a dict/ class instance), iterate on it, zipped with declared", "# - from an existing schema, have a way to \"restrict\" the field", "optimizations # - if input is a list ( and not a dict/", "zipped with declared fields. # - from an existing schema, have a way", "not a dict/ class instance), iterate on it, zipped with declared fields. #", "field to a \"smaller\" field. # A kind fo gradual typing i guess...", "a way to \"restrict\" the field to a \"smaller\" field. # A kind", "list ( and not a dict/ class instance), iterate on it, zipped with", "<reponame>asmodehn/aiokraken # TODO : Marshmallow schemas : Possible optimizations # - if input", "class instance), iterate on it, zipped with declared fields. # - from an", "if input is a list ( and not a dict/ class instance), iterate", "dict/ class instance), iterate on it, zipped with declared fields. # - from", ": Possible optimizations # - if input is a list ( and not", "is a list ( and not a dict/ class instance), iterate on it,", "instance), iterate on it, zipped with declared fields. # - from an existing", "with declared fields. # - from an existing schema, have a way to", "a list ( and not a dict/ class instance), iterate on it, zipped", "a dict/ class instance), iterate on it, zipped with declared fields. # -", "fields. # - from an existing schema, have a way to \"restrict\" the", "iterate on it, zipped with declared fields. # - from an existing schema,", "schema, have a way to \"restrict\" the field to a \"smaller\" field. #", "- if input is a list ( and not a dict/ class instance),", "an existing schema, have a way to \"restrict\" the field to a \"smaller\"", "declared fields. # - from an existing schema, have a way to \"restrict\"", "on it, zipped with declared fields. # - from an existing schema, have", "\"restrict\" the field to a \"smaller\" field. # A kind fo gradual typing", "to \"restrict\" the field to a \"smaller\" field. # A kind fo gradual", "existing schema, have a way to \"restrict\" the field to a \"smaller\" field.", "and not a dict/ class instance), iterate on it, zipped with declared fields.", "have a way to \"restrict\" the field to a \"smaller\" field. # A", "- from an existing schema, have a way to \"restrict\" the field to", "from an existing schema, have a way to \"restrict\" the field to a", "input is a list ( and not a dict/ class instance), iterate on", "Marshmallow schemas : Possible optimizations # - if input is a list (", "schemas : Possible optimizations # - if input is a list ( and" ]
[ "self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def", "from django.test import TestCase from .models import Place,Category,Image # Create your tests here.", "images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic' self.post.save() self.assertEqual(self.post.image,'newimagepic') def", "setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def", "ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self):", "Create your tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def", "self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all()", "def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food')", "import Place,Category,Image # Create your tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def", "# Create your tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place))", "def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi')", "import TestCase from .models import Place,Category,Image # Create your tests here. class PlaceTestClass(TestCase):", "self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all()", "self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice", "tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place()", "def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic'", "def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0)", "Place,Category,Image # Create your tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self):", "test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def", "self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food')", "setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def", "categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food)", "self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save()", "self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic' self.post.save() self.assertEqual(self.post.image,'newimagepic') def test_get_image_by_id(self):", "django.test import TestCase from .models import Place,Category,Image # Create your tests here. class", "self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self):", "TestCase from .models import Place,Category,Image # Create your tests here. class PlaceTestClass(TestCase): def", "test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic' self.post.save() self.assertEqual(self.post.image,'newimagepic') def test_get_image_by_id(self): image=Image.get_image_by_id(self.post.id) self.assertEqual(image,self.post)", "test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def", "self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self):", "your tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self):", "def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase):", "pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self):", "test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save()", "from .models import Place,Category,Image # Create your tests here. class PlaceTestClass(TestCase): def setUp(self):", "here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all()", ".models import Place,Category,Image # Create your tests here. class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi')", "self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic' self.post.save() self.assertEqual(self.post.image,'newimagepic')", "self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self):", "self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image()", "def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category))", "def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save()", "test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food", "test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def", "self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all()", "self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self):", "test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic' self.post.save()", "PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class", "self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self):", "food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0) def test_delete_image(self): Image.delete_image(self.post.id)", "CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0) class", "def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase):", "class ImageTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def", "def setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image))", "locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category()", "class PlaceTestClass(TestCase): def setUp(self): self.nairobi=Place(location='nairobi') def test_instance(self): self.assertTrue(isinstance(self.nairobi,Place)) def test_save_method(self): self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0)", "def test_delete_image(self): Image.delete_image(self.post.id) images=Image.objects.all() self.assertTrue(len(images)==0) def test_update_image(self): self.post.image='newimagepic' self.post.save() self.assertEqual(self.post.image,'newimagepic') def test_get_image_by_id(self): image=Image.get_image_by_id(self.post.id)", "self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def test_save_method(self): self.post.save_image() images=Image.objects.all() self.assertTrue(len(images)>0)", "setUp(self): self.nairobi=Place(location='nairobi') self.nairobi.save() self.food=Category(name='food') self.food.save() self.post=Image(image='imagepic',image_name='food pic',description='nice food',location=self.nairobi,category=self.food) self.post.save() def test_instance(self): self.assertTrue(isinstance(self.post,Image)) def", "class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self): self.food.save_category() categories=Category.objects.all() self.assertTrue(len(categories)>0)", "self.nairobi.save_place() locations=Place.objects.all() self.assertTrue(len(locations)>0) class CategoryTestClass(TestCase): def setUp(self): self.food=Category(name='food') def test_instance(self): self.assertTrue(isinstance(self.food,Category)) def test_save_method(self):" ]
[ "junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1:", "# logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING)", "status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) == 0:", "multiple=True) @click.pass_context def cli(ctx, services, services_path): # Create services context all_services = merge_yaml_sources(services,", "3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG)", "the result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind)", "cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock) cli.add_command(hello) if __name__ ==", "cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock) cli.add_command(hello) if __name__ == '__main__':", "@click.pass_context def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint", "ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) # # if len(verbose) >= 3: #", "@click.pass_context def put(ctx, path, destination): \"\"\"Put dixels at PATH in DESTINATION Orthanc service\"\"\"", "from diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind, pull", "pull from commands.splunk import sfind from commands.watch import watch from commands.mock import mock", "commands.watch import watch from commands.mock import mock from commands.hello import hello @click.group() @click.option('-s',", "# logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) #", "status') if len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints) for key in endpoints:", "diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind, pull from", "cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock) cli.add_command(hello) if __name__ == '__main__': cli(auto_envvar_prefix='DIANA')", "ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) == 0: endpoints =", "click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination))", "services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) #", "if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose) ==", "required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services,", "merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) # # if len(verbose) >=", "logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints',", "dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context", ">= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose) == 2: #", "from commands.watch import watch from commands.mock import mock from commands.hello import hello @click.group()", "status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if", "sfind from commands.watch import watch from commands.mock import mock from commands.hello import hello", "ofind, pull from commands.splunk import sfind from commands.watch import watch from commands.mock import", "@click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path): # Create", "logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR)", "= Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler,", "0: endpoints = services.keys() click.echo(endpoints) for key in endpoints: ep = Orthanc(**services[key]) click.echo(ep)", "Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path) D", "@click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path):", "S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx,", "endpoints = services.keys() click.echo(endpoints) for key in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info())", "= merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) # # if len(verbose)", "elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING)", "services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile() D.put(dixel,", "DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put", "'--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path): # Create services", "logging import click_log import click from diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources", "<reponame>derekmerck/DIANA import logging import click_log import click from diana.apis import * from utils.merge_yaml_sources", "services_path): # Create services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services", "from SOURCE Orthanc service and save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S", "process it with HANDLER, and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services =", "endpoint status') if len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints) for key in", "handler, source, destination): \"\"\"Retrieve a DIXEL from SOURCE, process it with HANDLER, and", "ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command()", "# logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def", "to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle)", "= Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid,", "= Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True))", "# # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif", "\"\"\"Get a dixel by OID from SOURCE Orthanc service and save to PATH\"\"\"", "logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report", "required=False) @click.option('-S', '--services_path', help='Path to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option()", "to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose", "Orthanc service and save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source))", "at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile()", "= ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints)", "(DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False)", "= S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def", "def get(ctx, oid, source, path): \"\"\"Get a dixel by OID from SOURCE Orthanc", "endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints)", "# else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1)", "services = ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel)", "destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source, destination):", "DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch)", "by OID from SOURCE Orthanc service and save to PATH\"\"\" click.echo(get.__doc__) services =", "merge_yaml_sources from commands.orthanc import ofind, pull from commands.splunk import sfind from commands.watch import", "len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else:", "SOURCE Orthanc service and save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S =", "logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) #", "# logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) #", "it with HANDLER, and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES']", "SOURCE, process it with HANDLER, and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services", "service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path) D =", "Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source,", "@click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a", "@click.pass_context def cli(ctx, services, services_path): # Create services context all_services = merge_yaml_sources(services, services_path)", "watch from commands.mock import mock from commands.hello import hello @click.group() @click.option('-s', '--services', help='Services", "'--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services file or directory", "import ofind, pull from commands.splunk import sfind from commands.watch import watch from commands.mock", "# @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path): #", "@click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source, path): \"\"\"Get a dixel", "\"\"\"Put dixels at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S", "destination): \"\"\"Retrieve a DIXEL from SOURCE, process it with HANDLER, and submit the", "S = Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path',", "type=click.File()) @click.pass_context def get(ctx, oid, source, path): \"\"\"Get a dixel by OID from", "logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx,", "# elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk output #", "ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel')", "= S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def", "path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put dixels at", "import sfind from commands.watch import watch from commands.mock import mock from commands.hello import", "services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock) cli.add_command(hello)", "click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock)", "commands.orthanc import ofind, pull from commands.splunk import sfind from commands.watch import watch from", "== 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING)", "oid, source, path): \"\"\"Get a dixel by OID from SOURCE Orthanc service and", "cli(ctx, services, services_path): # Create services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES']", "dixels at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S =", "@click.pass_context def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a DIXEL from SOURCE, process", "for key in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path',", "PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile() dixel", "help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path): # Create services context", "import mock from commands.hello import hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False)", "super-verbose\") # elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk output", "nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting", "path): \"\"\"Get a dixel by OID from SOURCE Orthanc service and save to", "commands.hello import hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path", "put(ctx, path, destination): \"\"\"Put dixels at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services", "with HANDLER, and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status)", "commands.mock import mock from commands.hello import hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)',", "ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints) for", "import * from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind, pull from commands.splunk", "type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put dixels at PATH in DESTINATION", "logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR)", "= all_services # print(len(verbose)) # # if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) #", "@click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source, path): \"\"\"Get a", "help='Path to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose',", "@click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put dixels at PATH in DESTINATION Orthanc", "all_services # print(len(verbose)) # # if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting", "@click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a DIXEL", "\"\"\"Retrieve a DIXEL from SOURCE, process it with HANDLER, and submit the result", "endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def", "DIXEL from SOURCE, process it with HANDLER, and submit the result to DESTINATION\"\"\"", "Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) ==", "@click.pass_context def get(ctx, oid, source, path): \"\"\"Get a dixel by OID from SOURCE", "click_log import click from diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc", "utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind, pull from commands.splunk import sfind from", "a DIXEL from SOURCE, process it with HANDLER, and submit the result to", "# Create services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services #", "click from diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind,", "= ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock) cli.add_command(hello) if", "output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: #", "Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination')", "from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind, pull from commands.splunk import sfind", "hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services", "* from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import ofind, pull from commands.splunk import", "from commands.mock import mock from commands.hello import hello @click.group() @click.option('-s', '--services', help='Services description", "and save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel =", "from commands.hello import hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path',", "OID from SOURCE Orthanc service and save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES']", "D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put dixels", "# logging.info(\"Setting super-verbose\") # elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce", "# logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING)", "click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source, path): \"\"\"Get", "@click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put dixels at PATH", "click.echo('Reporting endpoint status') if len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints) for key", "# print(len(verbose)) # # if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\")", "@click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services file", "@click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source, path): \"\"\"Get a dixel by OID", "# # if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif", "HANDLER, and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get)", "logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path): # Create services context all_services", "import logging import click_log import click from diana.apis import * from utils.merge_yaml_sources import", "def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a DIXEL from SOURCE, process it", "ctx.obj['SERVICES'] = all_services # print(len(verbose)) # # if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG)", "Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source,", "1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR)", "# Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose)", "# logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command()", "a dixel by OID from SOURCE Orthanc service and save to PATH\"\"\" click.echo(get.__doc__)", "DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path)", "import watch from commands.mock import mock from commands.hello import hello @click.group() @click.option('-s', '--services',", "len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints) for key in endpoints: ep =", "def cli(ctx, services, services_path): # Create services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict)", "= services.keys() click.echo(endpoints) for key in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command()", "@click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination): \"\"\"Put dixels at PATH in", "help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services file or directory (DIANA_SERVICES_PATH)',", "import click from diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources from commands.orthanc import", "# logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\"", "@click.option('-S', '--services_path', help='Path to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() #", "dixel = S.get(oid) D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context", "ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put) cli.add_command(handle) cli.add_command(watch) cli.add_command(mock) cli.add_command(hello) if __name__", "services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging',", "(DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def", "services, services_path): # Create services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] =", "services.keys() click.echo(endpoints) for key in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid')", "click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source, path):", "def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status')", "= ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile() D.put(dixel, path=path)", "all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) # # if", "source, destination): \"\"\"Retrieve a DIXEL from SOURCE, process it with HANDLER, and submit", "logging.basicConfig(level=logging.DEBUG) # # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) #", "services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) == 0: endpoints = services.keys()", "else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context", "logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) #", "click.echo(endpoints) for key in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source')", "source, path): \"\"\"Get a dixel by OID from SOURCE Orthanc service and save", "print(len(verbose)) # # if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") #", "directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context", "@click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a DIXEL from", "dixel by OID from SOURCE Orthanc service and save to PATH\"\"\" click.echo(get.__doc__) services", "# logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN)", "= DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source')", "S = DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler')", "result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull) cli.add_command(sfind) cli.add_command(put)", "handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a DIXEL from SOURCE, process it with", "import hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to", "ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx,", "service and save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel", "click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid) D = DicomFile()", "= DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path, destination):", "save to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid)", "S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx,", "= ctx.obj['SERVICES'] S = DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command()", "submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind) cli.add_command(pull)", "len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) #", "commands.splunk import sfind from commands.watch import watch from commands.mock import mock from commands.hello", "PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid) D =", "or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True)", "from commands.splunk import sfind from commands.watch import watch from commands.mock import mock from", "destination): \"\"\"Put dixels at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES']", "from SOURCE, process it with HANDLER, and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__)", "description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True),", "@click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES']", "file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True,", "import click_log import click from diana.apis import * from utils.merge_yaml_sources import merge_yaml_sources from", "in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File()) @click.pass_context", "dixel, handler, source, destination): \"\"\"Retrieve a DIXEL from SOURCE, process it with HANDLER,", "'--services_path', help='Path to services file or directory (DIANA_SERVICES_PATH)', type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v',", "of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) == 0: endpoints", "def put(ctx, path, destination): \"\"\"Put dixels at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__)", "# logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) #", "# logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints):", "key in endpoints: ep = Orthanc(**services[key]) click.echo(ep) click.echo(ep.info()) @click.command() @click.argument('oid') @click.argument('source') @click.argument('path', type=click.File())", "from commands.orthanc import ofind, pull from commands.splunk import sfind from commands.watch import watch", "2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) #", "mock from commands.hello import hello @click.group() @click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S',", "Create services context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose))", "logging.info(\"Setting super-verbose\") # elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # # Reduce junk", "logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) # #", "DicomFile() dixel = S.get(path) D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination')", "# logging.basicConfig(level=logging.DEBUG) # # Reduce junk output # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING)", "== 0: endpoints = services.keys() click.echo(endpoints) for key in endpoints: ep = Orthanc(**services[key])", "# if len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose)", "type=click.Path(exists=True), required=False) @click_log.simple_verbosity_option() # @click.option('-v', '--verbose', help='Verbose logging', is_flag=True, multiple=True) @click.pass_context def cli(ctx,", "# logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status", "logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status of", "\"\"\"Report status of ENDPOINTS\"\"\" services = ctx.obj['SERVICES'] click.echo('Reporting endpoint status') if len(endpoints) ==", "== 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: #", "and submit the result to DESTINATION\"\"\" click.echo(handle.__doc__) services = ctx.obj['SERVICES'] cli.add_command(status) cli.add_command(get) cli.add_command(ofind)", "D = DicomFile() D.put(dixel, path=path) @click.command() @click.argument('path', type=click.Path(exists=True)) @click.argument('destination') @click.pass_context def put(ctx, path,", "is_flag=True, multiple=True) @click.pass_context def cli(ctx, services, services_path): # Create services context all_services =", "in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services = ctx.obj['SERVICES'] S = DicomFile() dixel =", "D = Orthanc(**services.get(destination)) destination.put(dixel) @click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel,", "@click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services =", "@click.option('-s', '--services', help='Services description (DIANA_SERVICES)', required=False) @click.option('-S', '--services_path', help='Path to services file or", "# elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING)", "logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) #", "services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) # # if len(verbose) >= 3:", "# logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose) == 2: # logging.basicConfig(level=logging.DEBUG) #", "elif len(verbose) == 1: # logging.basicConfig(level=logging.WARN) # logging.getLogger(\"requests\").setLevel(logging.WARNING) # logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) #", "get(ctx, oid, source, path): \"\"\"Get a dixel by OID from SOURCE Orthanc service", "@click.command() @click.argument('dixel') @click.argument('handler') @click.argument('source') @click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve", "to PATH\"\"\" click.echo(get.__doc__) services = ctx.obj['SERVICES'] S = Orthanc(**services.get(source)) dixel = S.get(oid) D", "context all_services = merge_yaml_sources(services, services_path) ctx.ensure_object(dict) ctx.obj['SERVICES'] = all_services # print(len(verbose)) # #", "import merge_yaml_sources from commands.orthanc import ofind, pull from commands.splunk import sfind from commands.watch", "logging.getLogger(\"urllib3\").setLevel(logging.WARNING) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.WARNING) # else: # logging.basicConfig(level=logging.ERROR) # logging.getLogger(\"requests\").setLevel(logging.ERROR) # logging.getLogger(\"urllib3\").setLevel(logging.ERROR) # logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR)", "@click.argument('source') @click.argument('path', type=click.File()) @click.pass_context def get(ctx, oid, source, path): \"\"\"Get a dixel by", "path, destination): \"\"\"Put dixels at PATH in DESTINATION Orthanc service\"\"\" click.echo(__doc__) services =", "@click.argument('destination') @click.pass_context def handle(ctx, dixel, handler, source, destination): \"\"\"Retrieve a DIXEL from SOURCE,", "if len(endpoints) == 0: endpoints = services.keys() click.echo(endpoints) for key in endpoints: ep", "logging.getLogger(\"diana.utils.gateway.requester\").setLevel(logging.ERROR) @click.command() @click.argument('endpoints', nargs=-1) @click.pass_context def status(ctx, endpoints): \"\"\"Report status of ENDPOINTS\"\"\" services", "len(verbose) >= 3: # logging.basicConfig(level=logging.DEBUG) # logging.info(\"Setting super-verbose\") # elif len(verbose) == 2:" ]
[ "has 4' pony, so add 1' above grade + 1' header to wall", "area \", barea) sys.exit() # top floor exterior area difference from barea ta_delta", "if ta_delta < 0 else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area,", "= \"../../\" + fileid + \"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \"", "import photos import math, os, sys import xml.etree.ElementTree as ET FT_PER_M = 3.28084", "input(\"client info: \") (street, city, rest) = info.split(',') # skip over prov if", "H2K errror if perim <= 4*sqrt(area), common ratio is 1.05x # relevant for", "= info.split(',') # skip over prov if present - set in h2k template", "city # province set in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd", "NS\": rest = rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed", "above grade: \" + str(round(above_grade_sm * SF_PER_SM)) + \" below grade: \" +", "if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f", "perimeter operim = float(args.pop(1)) # foundation exterior area barea = float(args.pop(1)) if barea", "storeys == 1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation and", "sign since ta_delta can be negative if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta", "1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation and main floor", "len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f =", "\", \" + str(round(bfp_m * FT_PER_M)) + \", \" + str(round(bperim_in_m * FT_PER_M)))", "eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta", "rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM", "wall height # highest ceiling is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M +", "#t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if wall_height_m > 4", "(4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\")", "* SF_PER_SM)) + \", \" + str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\")", "+ \", \" + str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0)", "area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa =", "#sys.exit(0) # write prepared h2k file outfile = \"../../\" + fileid + \".h2k\"", "length: \" + str(round(ceiling_area_sm * SF_PER_SM)) + \", \" + str(round(c_len_m * FT_PER_M", "\" NS\": rest = rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy", "* SF_PER_SM))) # calculate volume 7.75ft bsmt + 1' header + 8ft main", "hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m * FT_PER_M )) + \", \" +", "different than fperim afl_perim = float(args.pop(1)) if len(args) == 1 else operim t", "+ str(round(volume * SF_PER_SM * FT_PER_M))) # calculate highest ceiling height # template", "perim: \" + str(round(bsmt_area_sm * SF_PER_SM )) + \", \" + str(round(bfp_m *", "St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info = input(\"client info: \") (street,", "perim, exp. surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM )) + \", \"", "1' header + 8ft main flr volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm)", "tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs house_data = \"../../\"", "file outfile = \"../../\" + fileid + \".h2k\" t.write(outfile, \"UTF-8\", True) #os.system(\"unix2dos \"", "floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area,", "exterior area difference from barea ta_delta = float(args.pop(1)) if len(args) > 1 else", "= hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if perim <= 4*sqrt(area), common", "t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys", "* FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2", "measurements\") sys.exit() args = sys.argv fileid = args.pop(1) template = args.pop(1) # wall", "= float(args.pop(1)) if len(args) > 1 else 0 # above foundation perimeter if", "str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if perim <=", "== 1 else operim t = ET.parse(template) # extract photos ymd = photos.extract(fileid)", "h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] =", "operim t = ET.parse(template) # extract photos ymd = photos.extract(fileid) # sample appointment", "# extract photos ymd = photos.extract(fileid) # sample appointment text: # 123 Main", "is exterior area so reduce by sqrt for rough interior area ta_sqrt =", "= FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if wall_height_m > 4 else", "0: # configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] =", "str(round(ceiling_area_sm * SF_PER_SM)) + \", \" + str(round(c_len_m * FT_PER_M ))) m =", "math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta is exterior area so reduce by", "2x6-house.txt \" + house_data) hd = open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text", "fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if wall_height_m >", "storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf", "postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt", "name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs house_data =", "ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) + tad_in_sm", "args = sys.argv fileid = args.pop(1) template = args.pop(1) # wall height in", "1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm # adjust for different top floor", "ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm * SF_PER_SM)) +", "main_area_sm if ta_delta < 0 else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling", "for semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m)", "template if rest[0:3] == \" NS\": rest = rest[3:] (postal, name, tel) =", "area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror", "c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta < 0", "SF_PER_SM)) + \" below grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume", "= str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm *", "Greener Homes wizard: creates H2K house models from templates import photos import math,", "tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm", "))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim:", "barea) sys.exit() # top floor exterior area difference from barea ta_delta = float(args.pop(1))", "float(args.pop(1))/FT_PER_M # outside foundation perimeter operim = float(args.pop(1)) # foundation exterior area barea", "area barea = float(args.pop(1)) if barea < 0: print(\"Invalid foundation area \", barea)", "# top floor exterior area difference from barea ta_delta = float(args.pop(1)) if len(args)", "ceiling is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = #", "print(\"Invalid foundation area \", barea) sys.exit() # top floor exterior area difference from", "str(round(bsmt_area_sm * SF_PER_SM )) + \", \" + str(round(bfp_m * FT_PER_M)) + \",", "= str(efl_m) hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm * SF_PER_SM)) + \",", "ta_delta < 0 else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length:", "hd.write(\"\\nfoundation floor area, perim, exp. surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM ))", "hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm * SF_PER_SM)) + \", \" + str(round(c_len_m", "tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume *", "reduce by sqrt for rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta", "name.split(' ')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text =", "ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta is exterior area so", "mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta < 0 else main_area_sm", "= (operim -8)/FT_PER_M # calculate sign since ta_delta can be negative if ta_delta", "\" + str(round(tad_in_sm * SF_PER_SM)) + \", \" + str(round(efl_m * FT_PER_M))) else:", "above foundation perimeter if different than fperim afl_perim = float(args.pop(1)) if len(args) ==", "FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M ** 2 if len(sys.argv) < 6: print(sys.argv[0],", "converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim", "to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM", "ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm", "= postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] =", "outside foundation perimeter operim = float(args.pop(1)) # foundation exterior area barea = float(args.pop(1))", "* FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared h2k file", "args.pop(1) # wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter", "fperim afl_perim = float(args.pop(1)) if len(args) == 1 else operim t = ET.parse(template)", "m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m * FT_PER_M )) +", "= t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"]", "= str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m * FT_PER_M", "+ str(mperim_in_m * FT_PER_M)) # calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m)", "1' above grade + 1' header to wall height # highest ceiling is", "wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter operim = float(args.pop(1)) # foundation exterior", "calculate foundation and main floor area converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM", "# configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m)", "+ str(round(tad_in_sm * SF_PER_SM)) + \", \" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef)", "SF_PER_SM * FT_PER_M))) # calculate highest ceiling height # template has 4' pony,", "= hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm =", "exterior area barea = float(args.pop(1)) if barea < 0: print(\"Invalid foundation area \",", "exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor", "print(\"f = foundation, t = top floor, outside measurements\") sys.exit() args = sys.argv", "= math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface", "SF_PER_SM )) + \", \" + str(round(bfp_m * FT_PER_M)) + \", \" +", "info = input(\"client info: \") (street, city, rest) = info.split(',') # skip over", "else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] =", "is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling)", "errror if perim <= 4*sqrt(area), common ratio is 1.05x # relevant for semis", "m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m *", "= t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta > 0: # configure exposed floor", "\", \" + str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) #", "grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft bsmt + 1'", "from barea ta_delta = float(args.pop(1)) if len(args) > 1 else 0 # above", "else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm", "+ str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m", "foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim,", "# write prepared h2k file outfile = \"../../\" + fileid + \".h2k\" t.write(outfile,", "top floor, outside measurements\") sys.exit() args = sys.argv fileid = args.pop(1) template =", "\" + str(mperim_in_m * FT_PER_M)) # calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] =", "ef = hc.find(\"Floor\") if ta_delta > 0: # configure exposed floor efl_m =", "ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta is", "floor area, length: \" + str(round(tad_in_sm * SF_PER_SM)) + \", \" + str(round(efl_m", "m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \"", "math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm =", "import xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M ** 2 if", "in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"]", "interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa", "= str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume * SF_PER_SM * FT_PER_M))) #", "= open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text =", "if ta_delta > 0: # configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] =", "rest) = info.split(',') # skip over prov if present - set in h2k", "rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs house_data = \"../../\" + fileid +", "< 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation,", "0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta is exterior area", "foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm)", "city, rest) = info.split(',') # skip over prov if present - set in", "* SF_PER_SM )) + \", \" + str(round(bfp_m * FT_PER_M)) + \", \"", "\" + str(round(volume * SF_PER_SM * FT_PER_M))) # calculate highest ceiling height #", "barea ta_delta = float(args.pop(1)) if len(args) > 1 else 0 # above foundation", "* ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"]", "below grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft bsmt +", "bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate sign since ta_delta can", "FT_PER_M))) # calculate highest ceiling height # template has 4' pony, so add", "+ \", \" + str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] =", "hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m)", "<NAME> 2021, 2022 # Greener Homes wizard: creates H2K house models from templates", "m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm", "+ str(round(bsmt_area_sm * SF_PER_SM )) + \", \" + str(round(bfp_m * FT_PER_M)) +", "#!/usr/bin/python # <NAME> 2021, 2022 # Greener Homes wizard: creates H2K house models", "args.pop(1) template = args.pop(1) # wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M #", "+ str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft bsmt + 1' header +", "rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs house_data = \"../../\" + fileid", "sqrt for rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt", "math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length: \" +", "set in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid", "* FT_PER_M)) # calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m =", "wizard: creates H2K house models from templates import photos import math, os, sys", "FT_PER_M)) # calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\")", "stick-framed 2x6 house specs house_data = \"../../\" + fileid + \"/\" + fileid", "if present - set in h2k template if rest[0:3] == \" NS\": rest", "\" + str(round(wall_height_m * FT_PER_M )) + \", \" + str(mperim_in_m * FT_PER_M))", "sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city # province set in", "photos import math, os, sys import xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM", "operim = float(args.pop(1)) # foundation exterior area barea = float(args.pop(1)) if barea <", "\"../../\" + fileid + \"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" +", "mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate", "extract photos ymd = photos.extract(fileid) # sample appointment text: # 123 Main St,", "by sqrt for rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta -", "7.75ft bsmt + 1' header + 8ft main flr volume = ((7.75 +", "+ wall_height_m * main_area_sm # adjust for different top floor area with 8'", "= # str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta > 0:", "volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm # adjust", "negative if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 #", "house_data = \"../../\" + fileid + \"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt", "fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd = open(house_data, 'a') hd.write(info)", "hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm * SF_PER_SM)) + \", \" +", "hd = open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text", "since ta_delta can be negative if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else:", "+ 1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm # adjust for different top", "grade + 1' header to wall height # highest ceiling is best calculated", "main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm *", "9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume * SF_PER_SM *", "best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc", "main floor area converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim", "* storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area", "perim: \" + str(round(wall_height_m * FT_PER_M )) + \", \" + str(mperim_in_m *", "= city # province set in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] =", "\" + str(round(bfp_m * FT_PER_M)) + \", \" + str(round(bperim_in_m * FT_PER_M))) #", "floor area, perim, exp. surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM )) +", "ceiling height # template has 4' pony, so add 1' above grade +", "os.system(\"cp 2x6-house.txt \" + house_data) hd = open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\")", "ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\")", "# outside foundation perimeter operim = float(args.pop(1)) # foundation exterior area barea =", "# Greener Homes wizard: creates H2K house models from templates import photos import", "1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface perim: \" +", "+ tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm * SF_PER_SM))", "FT_PER_M ** 2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea", "str(bsmt_area_sm) # H2K errror if perim <= 4*sqrt(area), common ratio is 1.05x #", "height # highest ceiling is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m", "# 123 Main St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info = input(\"client", "\" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft bsmt + 1' header", "# str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta > 0: #", "NS B1H 0H0 <NAME> 902-555-1212 info = input(\"client info: \") (street, city, rest)", "appointment text: # 123 Main St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info", "hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text", "* FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall", "storeys = 2 if wall_height_m > 4 else 1 # code 1 =", "if rest[0:3] == \" NS\": rest = rest[3:] (postal, name, tel) = rest[1:8],", "\"UTF-8\", True) #sys.exit(0) # write prepared h2k file outfile = \"../../\" + fileid", "= FT_PER_M ** 2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim", "= (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated", "templates import photos import math, os, sys import xml.etree.ElementTree as ET FT_PER_M =", "c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city #", "tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city # province set", "#t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta >", "bsmt + 1' header + 8ft main flr volume = ((7.75 + 1)/FT_PER_M", "bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp.", "outside measurements\") sys.exit() args = sys.argv fileid = args.pop(1) template = args.pop(1) #", "copy stick-framed 2x6 house specs house_data = \"../../\" + fileid + \"/\" +", "t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if", "than fperim afl_perim = float(args.pop(1)) if len(args) == 1 else operim t =", "main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m =", "SF_PER_SM))) # calculate volume 7.75ft bsmt + 1' header + 8ft main flr", "header + 8ft main flr volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm) +", "= (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate sign", "3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1 else \"3\"", "ta_delta > 0: # configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm)", "math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface perim:", "Homes wizard: creates H2K house models from templates import photos import math, os,", "if len(args) == 1 else operim t = ET.parse(template) # extract photos ymd", "= YearBuilt storeys = 2 if wall_height_m > 4 else 1 # code", "= mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta < 0 else", "2022 # Greener Homes wizard: creates H2K house models from templates import photos", "Main St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info = input(\"client info: \")", "prov if present - set in h2k template if rest[0:3] == \" NS\":", "= args.pop(1) template = args.pop(1) # wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M", "highest ceiling height # template has 4' pony, so add 1' above grade", "rest[0:3] == \" NS\": rest = rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:]", "str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade: \" + str(round(above_grade_sm", "# province set in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text", "relevant for semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] =", "wall_height_m > 4 else 1 # code 1 = 1 storey, 3 =", "== \" NS\": rest = rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] #", "# copy stick-framed 2x6 house specs house_data = \"../../\" + fileid + \"/\"", "= ((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm # adjust for", "- set in h2k template if rest[0:3] == \" NS\": rest = rest[3:]", "str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta > 0: # configure", "area sf above grade: \" + str(round(above_grade_sm * SF_PER_SM)) + \" below grade:", "present - set in h2k template if rest[0:3] == \" NS\": rest =", "afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M", "1 # code 1 = 1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] =", "height # template has 4' pony, so add 1' above grade + 1'", "+ \"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd =", "= str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade: \" +", "\", \" + str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m)", "skip over prov if present - set in h2k template if rest[0:3] ==", "SF_PER_SM)) + \", \" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\")", "< 0: print(\"Invalid foundation area \", barea) sys.exit() # top floor exterior area", "manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\")", "& area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K", "is 1.05x # relevant for semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 *", "hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta > 0: # configure exposed", "= rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs house_data = \"../../\" +", "afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation, t = top floor, outside", "\" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length", "multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area,", "ymd = photos.extract(fileid) # sample appointment text: # 123 Main St, Dartmouth, NS", "if storeys == 1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation", "= str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade: \" + str(round(above_grade_sm * SF_PER_SM))", "t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] =", "= \"../../\" + fileid + \".h2k\" t.write(outfile, \"UTF-8\", True) #os.system(\"unix2dos \" + outfile)", "str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume * SF_PER_SM * FT_PER_M))) # calculate", "# calculate sign since ta_delta can be negative if ta_delta != 0: ta_sign", "((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm # adjust for different", "1 = 1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys", "height in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter operim = float(args.pop(1))", "pony, so add 1' above grade + 1' header to wall height #", "t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta > 0: # configure exposed floor efl_m", "and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor", "in h2k template if rest[0:3] == \" NS\": rest = rest[3:] (postal, name,", "= str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface perim: \" + str(round(bsmt_area_sm *", "str(round(tad_in_sm * SF_PER_SM)) + \", \" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m", "m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta < 0 else main_area_sm +", "hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade: \" + str(round(above_grade_sm *", "!= 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta is exterior", "length: \" + str(round(tad_in_sm * SF_PER_SM)) + \", \" + str(round(efl_m * FT_PER_M)))", "# H2K errror if perim <= 4*sqrt(area), common ratio is 1.05x # relevant", "\", \" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave", "foundation area \", barea) sys.exit() # top floor exterior area difference from barea", "so reduce by sqrt for rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm =", "= str(bsmt_area_sm) # H2K errror if perim <= 4*sqrt(area), common ratio is 1.05x", "hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm", "= str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m * FT_PER_M )) + \",", "= rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house", "efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length:", "specs house_data = \"../../\" + fileid + \"/\" + fileid + \"-house-data.txt\" os.system(\"cp", "(postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs house_data", "sys.argv fileid = args.pop(1) template = args.pop(1) # wall height in metres wall_height_m", "rest = rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6", "2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1 else \"3\" hd.write(\"\\nstoreys: \"", "float(args.pop(1)) if len(args) == 1 else operim t = ET.parse(template) # extract photos", "rest[3:] (postal, name, tel) = rest[1:8], rest[9:-10],rest[-12:] # copy stick-framed 2x6 house specs", "calculate volume 7.75ft bsmt + 1' header + 8ft main flr volume =", "< 0 else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \"", "ta_delta = float(args.pop(1)) if len(args) > 1 else 0 # above foundation perimeter", "else 0 # above foundation perimeter if different than fperim afl_perim = float(args.pop(1))", "[ta_delta] [afl_perim]\") print(\"f = foundation, t = top floor, outside measurements\") sys.exit() args", "hc.find(\"Floor\") if ta_delta > 0: # configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"]", "+ 1' header + 8ft main flr volume = ((7.75 + 1)/FT_PER_M *", "perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) #", "ta_delta is exterior area so reduce by sqrt for rough interior area ta_sqrt", "info: \") (street, city, rest) = info.split(',') # skip over prov if present", "FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if wall_height_m > 4 else 1", "main flr volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm", "t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume * SF_PER_SM * FT_PER_M)))", "if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta", "# above foundation perimeter if different than fperim afl_perim = float(args.pop(1)) if len(args)", "info.split(',') # skip over prov if present - set in h2k template if", "ET.parse(template) # extract photos ymd = photos.extract(fileid) # sample appointment text: # 123", "1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1", "sa.find(\"Street\").text = street sa.find(\"City\").text = city # province set in h2k template sa.find(\"PostalCode\").text", "in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter operim = float(args.pop(1)) #", "xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M ** 2 if len(sys.argv)", "area, length: \" + str(round(tad_in_sm * SF_PER_SM)) + \", \" + str(round(efl_m *", "-operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate sign since ta_delta can be", "2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\")", "(ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys)", "above grade + 1' header to wall height # highest ceiling is best", "FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height,", "str(efl_m) hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm * SF_PER_SM)) + \", \"", "barea = float(args.pop(1)) if barea < 0: print(\"Invalid foundation area \", barea) sys.exit()", "c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city # province set in h2k template", "floor exterior area difference from barea ta_delta = float(args.pop(1)) if len(args) > 1", "\"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd = open(house_data, 'a') hd.write(info) c =", "str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length: \" + str(round(tad_in_sm * SF_PER_SM))", "import math, os, sys import xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM =", "ratio is 1.05x # relevant for semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4", "-4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate sign since ta_delta", "for rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt *", "highest ceiling is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] =", "* SF_PER_SM)) + \", \" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m =", "+ tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above", "= float(args.pop(1)) if len(args) == 1 else operim t = ET.parse(template) # extract", "ta_sign = 1 # ta_delta is exterior area so reduce by sqrt for", "storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1 else \"3\" hd.write(\"\\nstoreys: \" +", "hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation and main floor area converted to", "area, length: \" + str(round(ceiling_area_sm * SF_PER_SM)) + \", \" + str(round(c_len_m *", "photos.extract(fileid) # sample appointment text: # 123 Main St, Dartmouth, NS B1H 0H0", "= 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1 else \"3\" hd.write(\"\\nstoreys:", "- afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim", "str(round(wall_height_m * FT_PER_M )) + \", \" + str(mperim_in_m * FT_PER_M)) # calculate", "6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation, t", "sample appointment text: # 123 Main St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212", "for different top floor area with 8' ceiling and 1' floor volume +=", "wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if ta_delta", "c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel sa =", "# eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if", "+ 1' header to wall height # highest ceiling is best calculated manually", "#t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if wall_height_m > 4 else 1 #", "house_data) hd = open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0]", "over prov if present - set in h2k template if rest[0:3] == \"", "else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation and main floor area", "0: print(\"Invalid foundation area \", barea) sys.exit() # top floor exterior area difference", "= input(\"client info: \") (street, city, rest) = info.split(',') # skip over prov", "(main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor", "storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1 else", "- ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) +", "foundation perimeter operim = float(args.pop(1)) # foundation exterior area barea = float(args.pop(1)) if", "flr volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m * main_area_sm #", "+ fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd = open(house_data, 'a')", "if different than fperim afl_perim = float(args.pop(1)) if len(args) == 1 else operim", "perimeter if different than fperim afl_perim = float(args.pop(1)) if len(args) == 1 else", "fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation, t = top floor, outside measurements\")", "volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \" +", "FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared h2k file outfile", "== 1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation and main", "# highest ceiling is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"]", "* 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume * SF_PER_SM", "(operim -8)/FT_PER_M # calculate sign since ta_delta can be negative if ta_delta !=", "# wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter operim", "# relevant for semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"]", "FT_PER_M)) + \", \" + str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True)", "str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm * SF_PER_SM)) + \", \" +", "#t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared h2k file outfile = \"../../\" +", "= top floor, outside measurements\") sys.exit() args = sys.argv fileid = args.pop(1) template", "foundation, t = top floor, outside measurements\") sys.exit() args = sys.argv fileid =", "* 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface perim: \"", "len(args) > 1 else 0 # above foundation perimeter if different than fperim", "= tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city # province", "+ \", \" + str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") #", "if barea < 0: print(\"Invalid foundation area \", barea) sys.exit() # top floor", "top floor exterior area difference from barea ta_delta = float(args.pop(1)) if len(args) >", "+ \", \" + str(mperim_in_m * FT_PER_M)) # calculate foundation perim & area", "# skip over prov if present - set in h2k template if rest[0:3]", "[afl_perim]\") print(\"f = foundation, t = top floor, outside measurements\") sys.exit() args =", "adjust for different top floor area with 8' ceiling and 1' floor volume", "123 Main St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info = input(\"client info:", "math, os, sys import xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M", "\" + str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"]", "(afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate sign since", "floor area with 8' ceiling and 1' floor volume += tad_in_sm * 9/FT_PER_M", "street sa.find(\"City\").text = city # province set in h2k template sa.find(\"PostalCode\").text = postal", "template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation, t = top floor,", "-8)/FT_PER_M # calculate sign since ta_delta can be negative if ta_delta != 0:", "sa.find(\"City\").text = city # province set in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"]", "c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text =", "t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys == 1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys))", "# calculate highest ceiling height # template has 4' pony, so add 1'", "metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m", "2x6 house specs house_data = \"../../\" + fileid + \"/\" + fileid +", "len(args) == 1 else operim t = ET.parse(template) # extract photos ymd =", "template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection", "# debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared h2k file outfile =", "* bsmt_area_sm) + wall_height_m * main_area_sm # adjust for different top floor area", "= 2 if wall_height_m > 4 else 1 # code 1 = 1", "length c_len_m = mperim_in_m/2 m.attrib[\"length\"] = str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta <", "1 # ta_delta is exterior area so reduce by sqrt for rough interior", "= ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys =", "= hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \" +", "')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text =", "m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if perim <= 4*sqrt(area),", "floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \"", "ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2", "sys import xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M ** 2", "calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] =", "top floor area with 8' ceiling and 1' floor volume += tad_in_sm *", "and 1' floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume", "#highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\") ef", "prepared h2k file outfile = \"../../\" + fileid + \".h2k\" t.write(outfile, \"UTF-8\", True)", "\") (street, city, rest) = info.split(',') # skip over prov if present -", "ceiling_area_sm = main_area_sm if ta_delta < 0 else main_area_sm + tad_in_sm m.attrib[\"area\"] =", "print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation, t =", "\" + str(round(bsmt_area_sm * SF_PER_SM )) + \", \" + str(round(bfp_m * FT_PER_M))", "farea [ta_delta] [afl_perim]\") print(\"f = foundation, t = top floor, outside measurements\") sys.exit()", "= foundation, t = top floor, outside measurements\") sys.exit() args = sys.argv fileid", "= args.pop(1) # wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation", "<= 4*sqrt(area), common ratio is 1.05x # relevant for semis and multiple foundations", "creates H2K house models from templates import photos import math, os, sys import", "else operim t = ET.parse(template) # extract photos ymd = photos.extract(fileid) # sample", "= str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm * SF_PER_SM)) + \", \"", "= float(args.pop(1))/FT_PER_M # outside foundation perimeter operim = float(args.pop(1)) # foundation exterior area", "as ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M ** 2 if len(sys.argv) <", "t = top floor, outside measurements\") sys.exit() args = sys.argv fileid = args.pop(1)", "YearBuilt storeys = 2 if wall_height_m > 4 else 1 # code 1", "\"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate foundation and main floor area converted", "surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM )) + \", \" + str(round(bfp_m", "# sample appointment text: # 123 Main St, Dartmouth, NS B1H 0H0 <NAME>", "= 3.28084 SF_PER_SM = FT_PER_M ** 2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid", "area so reduce by sqrt for rough interior area ta_sqrt = math.sqrt(abs(ta_delta)) tad_in_sm", "<NAME> 902-555-1212 info = input(\"client info: \") (street, city, rest) = info.split(',') #", "+ str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared", "+ house_data) hd = open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split('", "outfile = \"../../\" + fileid + \".h2k\" t.write(outfile, \"UTF-8\", True) #os.system(\"unix2dos \" +", "+ str(round(wall_height_m * FT_PER_M )) + \", \" + str(mperim_in_m * FT_PER_M)) #", "write prepared h2k file outfile = \"../../\" + fileid + \".h2k\" t.write(outfile, \"UTF-8\",", "m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface perim: \" + str(round(bsmt_area_sm", "str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft bsmt + 1' header + 8ft", "<filename>ghwiz/ghwiz.py #!/usr/bin/python # <NAME> 2021, 2022 # Greener Homes wizard: creates H2K house", "B1H 0H0 <NAME> 902-555-1212 info = input(\"client info: \") (street, city, rest) =", "str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade: \" + str(round(above_grade_sm * SF_PER_SM)) +", "calculate sign since ta_delta can be negative if ta_delta != 0: ta_sign =", "m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm * SF_PER_SM)) + \",", "\", barea) sys.exit() # top floor exterior area difference from barea ta_delta =", "float(args.pop(1)) # foundation exterior area barea = float(args.pop(1)) if barea < 0: print(\"Invalid", "barea < 0: print(\"Invalid foundation area \", barea) sys.exit() # top floor exterior", "area with 8' ceiling and 1' floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"]", "+ wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\") ef = hc.find(\"Floor\") if", "hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if", "common ratio is 1.05x # relevant for semis and multiple foundations bfp_m =", ")) + \", \" + str(round(bfp_m * FT_PER_M)) + \", \" + str(round(bperim_in_m", "difference from barea ta_delta = float(args.pop(1)) if len(args) > 1 else 0 #", "= photos.extract(fileid) # sample appointment text: # 123 Main St, Dartmouth, NS B1H", "str(round(bfp_m * FT_PER_M)) + \", \" + str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\",", "= math.sqrt(abs(ta_delta)) tad_in_sm = (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm", "bperim_in_m = (operim -8)/FT_PER_M # calculate sign since ta_delta can be negative if", "\" + str(round(above_grade_sm * SF_PER_SM)) + \" below grade: \" + str(round(bsmt_area_sm *", "902-555-1212 info = input(\"client info: \") (street, city, rest) = info.split(',') # skip", "8ft main flr volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m *", "to wall height # highest ceiling is best calculated manually #highest_ceiling = (4+1+1)/FT_PER_M", "= 1 # ta_delta is exterior area so reduce by sqrt for rough", "8' ceiling and 1' floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume)", "str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m * FT_PER_M ))", "volume cf: \" + str(round(volume * SF_PER_SM * FT_PER_M))) # calculate highest ceiling", "hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m", "exterior area so reduce by sqrt for rough interior area ta_sqrt = math.sqrt(abs(ta_delta))", "with 8' ceiling and 1' floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] =", "= fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"] = YearBuilt storeys = 2 if wall_height_m", "1' header to wall height # highest ceiling is best calculated manually #highest_ceiling", "configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed", "# template has 4' pony, so add 1' above grade + 1' header", "template has 4' pony, so add 1' above grade + 1' header to", "hd.write(\"\\nheated floor area sf above grade: \" + str(round(above_grade_sm * SF_PER_SM)) + \"", "> 0: # configure exposed floor efl_m = math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"]", "= (ta_delta - ta_sqrt * ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm *", "0 else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" +", "= 1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if storeys ==", "= t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel", "+ str(round(above_grade_sm * SF_PER_SM)) + \" below grade: \" + str(round(bsmt_area_sm * SF_PER_SM)))", "cf: \" + str(round(volume * SF_PER_SM * FT_PER_M))) # calculate highest ceiling height", "* main_area_sm # adjust for different top floor area with 8' ceiling and", "# foundation exterior area barea = float(args.pop(1)) if barea < 0: print(\"Invalid foundation", "house models from templates import photos import math, os, sys import xml.etree.ElementTree as", "# code 1 = 1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\"", "c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street", "foundation perimeter if different than fperim afl_perim = float(args.pop(1)) if len(args) == 1", "floor, outside measurements\") sys.exit() args = sys.argv fileid = args.pop(1) template = args.pop(1)", "float(args.pop(1)) if barea < 0: print(\"Invalid foundation area \", barea) sys.exit() # top", "2021, 2022 # Greener Homes wizard: creates H2K house models from templates import", "SF_PER_SM)) + \", \" + str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"]", "1 else operim t = ET.parse(template) # extract photos ymd = photos.extract(fileid) #", "\"1\" if storeys == 1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) # calculate", "\" + str(storeys)) # calculate foundation and main floor area converted to metric", "so add 1' above grade + 1' header to wall height # highest", "# <NAME> 2021, 2022 # Greener Homes wizard: creates H2K house models from", "sf above grade: \" + str(round(above_grade_sm * SF_PER_SM)) + \" below grade: \"", "# calculate volume 7.75ft bsmt + 1' header + 8ft main flr volume", "# calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"]", "+ fileid + \"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data)", "= float(args.pop(1)) # foundation exterior area barea = float(args.pop(1)) if barea < 0:", "code 1 = 1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"] = \"1\" if", "= name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\")", "+1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea -operim +4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M #", "str(mperim_in_m * FT_PER_M)) # calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"] = str(bperim_in_m) m", "hd.write(\"\\nhouse volume cf: \" + str(round(volume * SF_PER_SM * FT_PER_M))) # calculate highest", "* SF_PER_SM * FT_PER_M))) # calculate highest ceiling height # template has 4'", "semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05 m.attrib[\"perimeter\"] = str(bfp_m) hd.write(\"\\nfoundation", "hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if perim <= 4*sqrt(area), common ratio", "str(round(volume * SF_PER_SM * FT_PER_M))) # calculate highest ceiling height # template has", "\", \" + str(mperim_in_m * FT_PER_M)) # calculate foundation perim & area hc.find(\"Basement\").attrib[\"exposedSurfacePerimeter\"]", "\"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd = open(house_data,", "1' floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf:", "4' pony, so add 1' above grade + 1' header to wall height", "afl_perim = float(args.pop(1)) if len(args) == 1 else operim t = ET.parse(template) #", "metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter operim = float(args.pop(1)) # foundation", "* SF_PER_SM)) + \" below grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate", "str(bfp_m) hd.write(\"\\nfoundation floor area, perim, exp. surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM", "ta_sign)/SF_PER_SM hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] =", "fileid = args.pop(1) template = args.pop(1) # wall height in metres wall_height_m =", "= (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc = t.find(\"House/Components\") ef =", "province set in h2k template sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text =", "\" below grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft bsmt", "str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta < 0 else main_area_sm + tad_in_sm m.attrib[\"area\"]", "4 else 1 # code 1 = 1 storey, 3 = 2 storey", "= \"1\" if storeys == 1 else \"3\" hd.write(\"\\nstoreys: \" + str(storeys)) #", "t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel sa", "2 if wall_height_m > 4 else 1 # code 1 = 1 storey,", "> 1 else 0 # above foundation perimeter if different than fperim afl_perim", "if wall_height_m > 4 else 1 # code 1 = 1 storey, 3", "+ \", \" + str(round(bfp_m * FT_PER_M)) + \", \" + str(round(bperim_in_m *", "sa.find(\"PostalCode\").text = postal t.find(\"ProgramInformation/File\").attrib[\"evaluationDate\"] = ymd t.find(\"ProgramInformation/File/Identification\").text = fileid #t.find(\"./House/Specifications/FacingDirection\").attrib[\"code\"] = FacingDirection #t.find(\"./House/Specifications/YearBuilt\").attrib[\"value\"]", "wall_height_m * main_area_sm # adjust for different top floor area with 8' ceiling", "= sys.argv fileid = args.pop(1) template = args.pop(1) # wall height in metres", "+ str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] =", "hfa = t.find(\"House/Specifications/HeatedFloorArea\") above_grade_sm = (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm)", "str(storeys)) # calculate foundation and main floor area converted to metric main_area_sm=(barea -", ")) + \", \" + str(mperim_in_m * FT_PER_M)) # calculate foundation perim &", "foundation and main floor area converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m", "= hc.find(\"Floor\") if ta_delta > 0: # configure exposed floor efl_m = math.sqrt(tad_in_sm)", "tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm) hd.write(\"\\nceiling area, length: \" + str(round(ceiling_area_sm * SF_PER_SM)) +", "+4)/SF_PER_SM bperim_in_m = (operim -8)/FT_PER_M # calculate sign since ta_delta can be negative", "fileid + \"/\" + fileid + \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd", "open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split('", "# ta_delta is exterior area so reduce by sqrt for rough interior area", "ceiling and 1' floor volume += tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse", "else 1 # code 1 = 1 storey, 3 = 2 storey t.find(\"House/Specifications/Storeys\").attrib[\"code\"]", "str(mperim_in_m) hd.write(\"\\nwall height, perim: \" + str(round(wall_height_m * FT_PER_M )) + \", \"", "4*sqrt(area), common ratio is 1.05x # relevant for semis and multiple foundations bfp_m", "\" + str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write", "house specs house_data = \"../../\" + fileid + \"/\" + fileid + \"-house-data.txt\"", "* FT_PER_M)) + \", \" + str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\",", "can be negative if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign =", "main_area_sm # adjust for different top floor area with 8' ceiling and 1'", "m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if perim <= 4*sqrt(area), common ratio is", "str(round(above_grade_sm * SF_PER_SM)) + \" below grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) #", "# adjust for different top floor area with 8' ceiling and 1' floor", "sys.exit() args = sys.argv fileid = args.pop(1) template = args.pop(1) # wall height", "calculated manually #highest_ceiling = (4+1+1)/FT_PER_M + wall_height_m #t.find(\"House/NaturalAirInfiltration/Specifications/BuildingSite\").attrib[\"highestCeiling\"] = # str(highest_ceiling) hc =", "= c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city # province set in h2k", "= math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1 # ta_delta is exterior area so reduce", "= math.sqrt(tad_in_sm) ef.find(\"Measurements\").attrib[\"area\"] = str(tad_in_sm) ef.find(\"Measurements\").attrib[\"length\"] = str(efl_m) hd.write(\"\\nexposed floor area, length: \"", "+ 8ft main flr volume = ((7.75 + 1)/FT_PER_M * bsmt_area_sm) + wall_height_m", "bsmt_area_sm) + wall_height_m * main_area_sm # adjust for different top floor area with", "set in h2k template if rest[0:3] == \" NS\": rest = rest[3:] (postal,", "template = args.pop(1) # wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside", "+= tad_in_sm * 9/FT_PER_M t.find(\"House/NaturalAirInfiltration/Specifications/House\").attrib[\"volume\"] = str(volume) hd.write(\"\\nhouse volume cf: \" + str(round(volume", "from templates import photos import math, os, sys import xml.etree.ElementTree as ET FT_PER_M", "= float(args.pop(1)) if barea < 0: print(\"Invalid foundation area \", barea) sys.exit() #", "floor area sf above grade: \" + str(round(above_grade_sm * SF_PER_SM)) + \" below", "= name.split(' ')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text", "name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text", "volume 7.75ft bsmt + 1' header + 8ft main flr volume = ((7.75", "os, sys import xml.etree.ElementTree as ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M **", "if perim <= 4*sqrt(area), common ratio is 1.05x # relevant for semis and", "+ str(round(bfp_m * FT_PER_M)) + \", \" + str(round(bperim_in_m * FT_PER_M))) # debug", "tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade:", "* FT_PER_M))) # calculate highest ceiling height # template has 4' pony, so", "1 else 0 # above foundation perimeter if different than fperim afl_perim =", "FT_PER_M )) + \", \" + str(mperim_in_m * FT_PER_M)) # calculate foundation perim", "* FT_PER_M )) + \", \" + str(mperim_in_m * FT_PER_M)) # calculate foundation", "\" + str(round(ceiling_area_sm * SF_PER_SM)) + \", \" + str(round(c_len_m * FT_PER_M )))", "photos ymd = photos.extract(fileid) # sample appointment text: # 123 Main St, Dartmouth,", "+ \"-house-data.txt\" os.system(\"cp 2x6-house.txt \" + house_data) hd = open(house_data, 'a') hd.write(info) c", "area difference from barea ta_delta = float(args.pop(1)) if len(args) > 1 else 0", "models from templates import photos import math, os, sys import xml.etree.ElementTree as ET", "+ str(storeys)) # calculate foundation and main floor area converted to metric main_area_sm=(barea", "= street sa.find(\"City\").text = city # province set in h2k template sa.find(\"PostalCode\").text =", "text: # 123 Main St, Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info =", "3.28084 SF_PER_SM = FT_PER_M ** 2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k", "float(args.pop(1)) if len(args) > 1 else 0 # above foundation perimeter if different", "0 # above foundation perimeter if different than fperim afl_perim = float(args.pop(1)) if", "'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text = name.split(' ')[0] c.find(\"Name/Last\").text = name.split(' ')[1]", "= str(c_len_m) ceiling_area_sm = main_area_sm if ta_delta < 0 else main_area_sm + tad_in_sm", "= str(bperim_in_m) m = hc.find(\"Basement/Floor/Measurements\") m.attrib[\"area\"] = str(bsmt_area_sm) # H2K errror if perim", "Dartmouth, NS B1H 0H0 <NAME> 902-555-1212 info = input(\"client info: \") (street, city,", "\" + house_data) hd = open(house_data, 'a') hd.write(info) c = t.find(\"./ProgramInformation/Client\") c.find(\"Name/First\").text =", "str(round(bperim_in_m * FT_PER_M))) # debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared h2k", "if len(args) > 1 else 0 # above foundation perimeter if different than", "perim <= 4*sqrt(area), common ratio is 1.05x # relevant for semis and multiple", "+ str(round(ceiling_area_sm * SF_PER_SM)) + \", \" + str(round(c_len_m * FT_PER_M ))) m", "h2k file outfile = \"../../\" + fileid + \".h2k\" t.write(outfile, \"UTF-8\", True) #os.system(\"unix2dos", "be negative if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign = 1", "floor area converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M", "hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm) hd.write(\"\\nheated floor area sf above grade: \"", "else: ta_sign = 1 # ta_delta is exterior area so reduce by sqrt", "exp. surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM )) + \", \" +", "= main_area_sm if ta_delta < 0 else main_area_sm + tad_in_sm m.attrib[\"area\"] = str(ceiling_area_sm)", "height, perim: \" + str(round(wall_height_m * FT_PER_M )) + \", \" + str(mperim_in_m", "sys.exit() # top floor exterior area difference from barea ta_delta = float(args.pop(1)) if", "0H0 <NAME> 902-555-1212 info = input(\"client info: \") (street, city, rest) = info.split(',')", "str(round(c_len_m * FT_PER_M ))) m = hc.find(\"Wall/Measurements\") m.attrib[\"height\"] = str(wall_height_m) m.attrib[\"perimeter\"] = str(mperim_in_m)", "ET FT_PER_M = 3.28084 SF_PER_SM = FT_PER_M ** 2 if len(sys.argv) < 6:", "SF_PER_SM = FT_PER_M ** 2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height", "different top floor area with 8' ceiling and 1' floor volume += tad_in_sm", "\"fileid template.h2k afl-height fperim farea [ta_delta] [afl_perim]\") print(\"f = foundation, t = top", "h2k template if rest[0:3] == \" NS\": rest = rest[3:] (postal, name, tel)", "calculate highest ceiling height # template has 4' pony, so add 1' above", "+ \" below grade: \" + str(round(bsmt_area_sm * SF_PER_SM))) # calculate volume 7.75ft", "FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m = mperim_in_m/2 m.attrib[\"length\"]", "foundation exterior area barea = float(args.pop(1)) if barea < 0: print(\"Invalid foundation area", "# calculate foundation and main floor area converted to metric main_area_sm=(barea - afl_perim/2", "** 2 if len(sys.argv) < 6: print(sys.argv[0], \"fileid template.h2k afl-height fperim farea [ta_delta]", "wall height in metres wall_height_m = float(args.pop(1))/FT_PER_M # outside foundation perimeter operim =", "area converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m = (afl_perim -4)/FT_PER_M bsmt_area_sm=(barea", "header to wall height # highest ceiling is best calculated manually #highest_ceiling =", "debug #t.write(\"out.h2k\", \"UTF-8\", True) #sys.exit(0) # write prepared h2k file outfile = \"../../\"", "')[1] c.find(\"Telephone\").text = tel sa = c.find(\"StreetAddress\") sa.find(\"Street\").text = street sa.find(\"City\").text = city", "str(round(efl_m * FT_PER_M))) else: hc.remove(ef) m = hc.find(\"Ceiling/Measurements\") # eave length c_len_m =", "True) #sys.exit(0) # write prepared h2k file outfile = \"../../\" + fileid +", "t = ET.parse(template) # extract photos ymd = photos.extract(fileid) # sample appointment text:", "H2K house models from templates import photos import math, os, sys import xml.etree.ElementTree", "(street, city, rest) = info.split(',') # skip over prov if present - set", "> 4 else 1 # code 1 = 1 storey, 3 = 2", "and main floor area converted to metric main_area_sm=(barea - afl_perim/2 +1)/SF_PER_SM mperim_in_m =", "above_grade_sm = (main_area_sm * storeys) + tad_in_sm hfa.attrib[\"aboveGrade\"] = str(above_grade_sm) hfa.attrib[\"belowGrade\"] = str(bsmt_area_sm)", "grade: \" + str(round(above_grade_sm * SF_PER_SM)) + \" below grade: \" + str(round(bsmt_area_sm", "1.05x # relevant for semis and multiple foundations bfp_m = math.sqrt(bsmt_area_sm)*4 * 1.05", "ta_delta can be negative if ta_delta != 0: ta_sign = math.sqrt(pow(ta_delta,2))/ta_delta else: ta_sign", "add 1' above grade + 1' header to wall height # highest ceiling", "area, perim, exp. surface perim: \" + str(round(bsmt_area_sm * SF_PER_SM )) + \",", "= ET.parse(template) # extract photos ymd = photos.extract(fileid) # sample appointment text: #" ]
[ "up to 3 decimal places from 0.0001-1. Returns the value maximizes macro f1", "import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc from sklearn.metrics import", "sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics", "from sklearn.metrics import roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from", "error: raise Exception('Caught this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts", "= prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc =", "threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix]", "np.arange(0, 1, 0.0001) # evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro')", "score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except", "scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in thresholds] # get best", "predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels,", "t), average='macro') for t in thresholds] # get best threshold ix = np.argmax(scores)", "not threshold else None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions =", "thresholds = np.arange(0, 1, 0.0001) # evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs,", "= [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in thresholds] # get best threshold", "prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score", "values up to 3 decimal places from 0.0001-1. Returns the value maximizes macro", "recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix", "save_path) #threshold = round(thresholds[ix], 3) if not threshold else None if not threshold:", "from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from", "repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\"", "= matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return", "average='macro') for t in thresholds] # get best threshold ix = np.argmax(scores) print('Threshold=%.3f,", "ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except", "mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels,", "y_test:list)->float: \"\"\" Extracts cut off thresholds by itrating all possible values up to", "(2 * precision * recall) / (precision + recall) # locate the index", "test_set:list -> original target values prediction_proba:list -> extension to use for serializing labels:list", "of the largest f score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix],", "from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from", "None)->dict: \"\"\" Args: test_set:list -> original target values prediction_proba:list -> extension to use", "np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision,", "return thresholds[ix] except Exception as error: raise Exception('Caught this error: ' + repr(error))", "roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba)", "+ recall) # locate the index of the largest f score ix =", "fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr)", "thresholds] # get best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' %", "print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix':", "target values prediction_proba:list -> extension to use for serializing labels:list -> target label", "np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except Exception as error:", "classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews", "-> roc or precision-recall save_path:str -> save directory \"\"\" try: auc_score = 0", "import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int')", "return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to f", "(thresholds[ix], scores[ix])) return thresholds[ix] except Exception as error: raise Exception('Caught this error: '", "-> original target values prediction_proba:list -> extension to use for serializing labels:list ->", "prediction_proba:list -> extension to use for serializing labels:list -> target label names threshold:float", "thresholds thresholds = np.arange(0, 1, 0.0001) # evaluate each threshold scores = [f1_score(y_test,", "from scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def", "coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set,", "threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in thresholds] # get", "all possible values up to 3 decimal places from 0.0001-1. Returns the value", "roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix", "directory \"\"\" try: auc_score = 0 if plot=='roc': fpr, tpr, _ = roc_curve(test_set,", "(precision + recall) # locate the index of the largest f score ix", "* precision * recall) / (precision + recall) # locate the index of", "from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef from", "threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm", "names threshold:float -> Probability cut off threshold plot:str -> roc or precision-recall save_path:str", "0.0001-1. Returns the value maximizes macro f1 score. \"\"\" try: # define thresholds", "scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >=", "threshold:float -> Probability cut off threshold plot:str -> roc or precision-recall save_path:str ->", "cut off threshold plot:str -> roc or precision-recall save_path:str -> save directory \"\"\"", "error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str", "sklearn.metrics import precision_recall_curve from sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics", "values prediction_proba:list -> extension to use for serializing labels:list -> target label names", "= auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos =", "= round(thresholds[ix], 3) if not threshold else None if not threshold: threshold =", "plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return", "* recall) / (precision + recall) # locate the index of the largest", "None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr =", "possible values up to 3 decimal places from 0.0001-1. Returns the value maximizes", "f score fscore = (2 * precision * recall) / (precision + recall)", "' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds by itrating", "= None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list -> original target values", "if plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score,", ">= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to f score fscore", "plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try:", "auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve", "labels:list -> target label names threshold:float -> Probability cut off threshold plot:str ->", "sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc from sklearn.metrics", "to f score fscore = (2 * precision * recall) / (precision +", "scores[ix])) return thresholds[ix] except Exception as error: raise Exception('Caught this error: ' +", "ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos,", "# define thresholds thresholds = np.arange(0, 1, 0.0001) # evaluate each threshold scores", "= None)->dict: \"\"\" Args: test_set:list -> original target values prediction_proba:list -> extension to", "= get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0],", "to use for serializing labels:list -> target label names threshold:float -> Probability cut", "raise Exception('Caught this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut", "labels:list, threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list -> original", "original target values prediction_proba:list -> extension to use for serializing labels:list -> target", "= np.arange(0, 1, 0.0001) # evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs, t),", "= np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except Exception", "= roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set,", "numpy as np from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics", "'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as error: raise Exception('Caught this error: '", "precision * recall) / (precision + recall) # locate the index of the", "cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ',", "np from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc", "'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as error: raise", "1, 0.0001) # evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for", "3 decimal places from 0.0001-1. Returns the value maximizes macro f1 score. \"\"\"", "accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef", "cr = classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions)", "predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation", "roc or precision-recall save_path:str -> save directory \"\"\" try: auc_score = 0 if", "thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix =", "correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm,", "precision_recall_curve from sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score", "def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: #", "None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list -> original target values prediction_proba:list", "threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to", "auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos", "print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except Exception as error:", "plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score =", "auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix],", "(thresholds[ix], fscore[ix])) return ix except Exception as error: raise Exception('Caught this error: '", "import precision_recall_curve from sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics import", "-> Probability cut off threshold plot:str -> roc or precision-recall save_path:str -> save", "0 if plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba)", "to 3 decimal places from 0.0001-1. Returns the value maximizes macro f1 score.", "# locate the index of the largest f score ix = np.argmax(fscore) print('PR-curve", "recall) / (precision + recall) # locate the index of the largest f", "sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from scripts.visualization", "recall:list, thresholds:list)->int: try: # convert to f score fscore = (2 * precision", "return ix except Exception as error: raise Exception('Caught this error: ' + repr(error))", "= classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr)", "f1_score from scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix", "' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str =", "as error: raise Exception('Caught this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\"", "plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill =", "serializing labels:list -> target label names threshold:float -> Probability cut off threshold plot:str", "np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except Exception as", "def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds by itrating all possible values", "from sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from", "score fscore = (2 * precision * recall) / (precision + recall) #", "from scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs", "cut off thresholds by itrating all possible values up to 3 decimal places", "t in thresholds] # get best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro", "if not threshold else None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions", "= roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision,", "plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3) if not", "or precision-recall save_path:str -> save directory \"\"\" try: auc_score = 0 if plot=='roc':", "fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall,", "\"\"\" try: auc_score = 0 if plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba)", "Exception as error: raise Exception('Caught this error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list,", "prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set,", "confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm,", "this error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall',", "= get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm =", "classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve", "{'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as error:", "Probability cut off threshold plot:str -> roc or precision-recall save_path:str -> save directory", "recall) # locate the index of the largest f score ix = np.argmax(fscore)", "try: # define thresholds thresholds = np.arange(0, 1, 0.0001) # evaluate each threshold", "from sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score from", "# evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in", "macro f1 score. \"\"\" try: # define thresholds thresholds = np.arange(0, 1, 0.0001)", "precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3) if not threshold else", "% (thresholds[ix], fscore[ix])) return ix except Exception as error: raise Exception('Caught this error:", "def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args:", "-> target label names threshold:float -> Probability cut off threshold plot:str -> roc", "= (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix],", "_ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall':", "sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve from scripts.visualization", "threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels)", "(recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3)", "maximizes macro f1 score. \"\"\" try: # define thresholds thresholds = np.arange(0, 1,", "#threshold = round(thresholds[ix], 3) if not threshold else None if not threshold: threshold", "0.0001) # evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t", "plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list -> original target values prediction_proba:list ->", "f score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix", "thresholds:list)->int: try: # convert to f score fscore = (2 * precision *", "sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization", "thresholds by itrating all possible values up to 3 decimal places from 0.0001-1.", "precision-recall save_path:str -> save directory \"\"\" try: auc_score = 0 if plot=='roc': fpr,", "from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list,", "= 0 if plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set,", "import auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics import", "'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as error: raise Exception('Caught this", "roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score", "try: auc_score = 0 if plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score", "predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score,", "get best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix]))", "save_path:str -> save directory \"\"\" try: auc_score = 0 if plot=='roc': fpr, tpr,", "Exception as error: raise Exception('Caught this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float:", "get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2),", "save directory \"\"\" try: auc_score = 0 if plot=='roc': fpr, tpr, _ =", "from 0.0001-1. Returns the value maximizes macro f1 score. \"\"\" try: # define", "Extracts cut off thresholds by itrating all possible values up to 3 decimal", "save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception", "label names threshold:float -> Probability cut off threshold plot:str -> roc or precision-recall", "else None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr", "by itrating all possible values up to 3 decimal places from 0.0001-1. Returns", "import f1_score from scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization import", "decimal places from 0.0001-1. Returns the value maximizes macro f1 score. \"\"\" try:", "= np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall,", "\"\"\" Extracts cut off thresholds by itrating all possible values up to 3", "plot:str -> roc or precision-recall save_path:str -> save directory \"\"\" try: auc_score =", "in thresholds] # get best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f'", "not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr = classification_report(test_set, predictions,", "convert to f score fscore = (2 * precision * recall) / (precision", "-> save directory \"\"\" try: auc_score = 0 if plot=='roc': fpr, tpr, _", "thresholds[ix] except Exception as error: raise Exception('Caught this error: ' + repr(error)) def", "mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path)", "save_path:str = None)->dict: \"\"\" Args: test_set:list -> original target values prediction_proba:list -> extension", "fscore[ix])) return ix except Exception as error: raise Exception('Caught this error: ' +", "plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def", "largest f score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return", "-> extension to use for serializing labels:list -> target label names threshold:float ->", "extension to use for serializing labels:list -> target label names threshold:float -> Probability", "Exception('Caught this error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None,", "= (2 * precision * recall) / (precision + recall) # locate the", "as np from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import", "prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list ->", "get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to f score fscore = (2 *", "error: raise Exception('Caught this error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float", "\"\"\" Args: test_set:list -> original target values prediction_proba:list -> extension to use for", "recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path)", "def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to f score fscore = (2", "ix except Exception as error: raise Exception('Caught this error: ' + repr(error)) def", "= confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc)", "the index of the largest f score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f'", "= np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except Exception as", "use for serializing labels:list -> target label names threshold:float -> Probability cut off", "from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve from", "define thresholds thresholds = np.arange(0, 1, 0.0001) # evaluate each threshold scores =", "round(thresholds[ix], 3) if not threshold else None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba,", "print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc,", "sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import classification_report from sklearn.metrics", "predictions = prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions) mcc", "to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert", "from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import classification_report from", "get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list", "for t in thresholds] # get best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best", "import matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import", "import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int:", "itrating all possible values up to 3 decimal places from 0.0001-1. Returns the", "prediction_proba) auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds)", "3) if not threshold else None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set)", "\"\"\" try: # define thresholds thresholds = np.arange(0, 1, 0.0001) # evaluate each", "Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except Exception as error: raise", "+ repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds by itrating all", "fscore = (2 * precision * recall) / (precision + recall) # locate", "roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall,", "prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds", "round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3) if not threshold else None if", "labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except", "threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except Exception as error: raise Exception('Caught", "scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs,", "Args: test_set:list -> original target values prediction_proba:list -> extension to use for serializing", "best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return", "predictions, target_names=labels, output_dict=True)} except Exception as error: raise Exception('Caught this error: ' +", "return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as", "repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds by itrating all possible", "tpr) elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision)", "no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score,", "recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3) if not threshold", "# get best threshold ix = np.argmax(scores) print('Threshold=%.3f, Best macro F1-Score=%.5f' % (thresholds[ix],", "import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import classification_report from sklearn.metrics import", "auc_score = 0 if plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score =", "try: # convert to f score fscore = (2 * precision * recall)", "matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient: ', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold,", "except Exception as error: raise Exception('Caught this error: ' + repr(error)) def get_evaluation_report(test_set:list,", "as error: raise Exception('Caught this error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list,", "cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as error: raise Exception('Caught this error:", "best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3) if not threshold else None", "the value maximizes macro f1 score. \"\"\" try: # define thresholds thresholds =", "ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except Exception", "each threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in thresholds] #", "evaluate each threshold scores = [f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in thresholds]", "threshold else None if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold", "import numpy as np from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from", "except Exception as error: raise Exception('Caught this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list,", "get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds by itrating all possible values up", "auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif plot=='precision-recall': precision, recall, thresholds =", "places from 0.0001-1. Returns the value maximizes macro f1 score. \"\"\" try: #", "index of the largest f score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' %", "value maximizes macro f1 score. \"\"\" try: # define thresholds thresholds = np.arange(0,", "import roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import", "this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds", "precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall, thresholds) best_threshold_pos = (recall[ix], precision[ix])", "if not threshold: threshold = get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr = classification_report(test_set,", "/ (precision + recall) # locate the index of the largest f score", "import plot_roc_curve from scripts.visualization import plot_precision_recall_curve from scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold):", "target_names=labels, output_dict=True)} except Exception as error: raise Exception('Caught this error: ' + repr(error))", "matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import classification_report", "[f1_score(y_test, to_labels(pos_probs, t), average='macro') for t in thresholds] # get best threshold ix", "from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc from", "off thresholds by itrating all possible values up to 3 decimal places from", "f1 score. \"\"\" try: # define thresholds thresholds = np.arange(0, 1, 0.0001) #", "for serializing labels:list -> target label names threshold:float -> Probability cut off threshold", "import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from scripts.visualization import", "precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision, recall,", "plot=='roc': fpr, tpr, _ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr,", "the largest f score ix = np.argmax(fscore) print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix]))", "# convert to f score fscore = (2 * precision * recall) /", "best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold =", "Exception('Caught this error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off", "import confusion_matrix from sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve from scripts.visualization import", "raise Exception('Caught this error: ' + repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float =", "precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold = round(thresholds[ix], 3) if", "% (thresholds[ix], scores[ix])) return thresholds[ix] except Exception as error: raise Exception('Caught this error:", "thresholds) best_threshold_pos = (recall[ix], precision[ix]) plot_precision_recall_curve(auc_score, recall, precision, best_threshold_pos, round(no_skill[0], 2), save_path) #threshold", "= precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape ix = get_cut_off_threshold_from_precision_recall(precision,", "confusion_matrix from sklearn.metrics import f1_score from scripts.visualization import plot_roc_curve from scripts.visualization import plot_precision_recall_curve", "print('PR-curve threshold=%f, F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except Exception as error: raise", "sklearn.metrics import auc from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score from sklearn.metrics", "threshold plot:str -> roc or precision-recall save_path:str -> save directory \"\"\" try: auc_score", "error: ' + repr(error)) def get_cut_off_threshold_through_iteration(pos_probs:list, y_test:list)->float: \"\"\" Extracts cut off thresholds by", "(pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to f score", "', mcc) plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions,", "target_names=labels) cm = confusion_matrix(test_set, predictions) mcc = matthews_corrcoef(test_set, predictions) print('\\n',cr) print('Matthews correlation coefficient:", "+ repr(error)) def get_evaluation_report(test_set:list, prediction_proba:list, labels:list, threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict:", "threshold:float = None, plot:str='precision-recall', save_path:str = None)->dict: \"\"\" Args: test_set:list -> original target", "target label names threshold:float -> Probability cut off threshold plot:str -> roc or", "2), save_path) #threshold = round(thresholds[ix], 3) if not threshold else None if not", "off threshold plot:str -> roc or precision-recall save_path:str -> save directory \"\"\" try:", "sklearn.metrics import roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics", "test_set) predictions = prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set, predictions)", "to_labels(pos_probs, t), average='macro') for t in thresholds] # get best threshold ix =", "plot_confusion_matrix(cm, labels, save_path=save_path) return {'threshold':threshold, 'auc':auc_score, 'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)}", "precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill = np.sum(test_set==1)/test_set.shape", "F-Score=%.3f' % (thresholds[ix], fscore[ix])) return ix except Exception as error: raise Exception('Caught this", "F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except Exception as error: raise Exception('Caught this", "scripts.visualization import plot_confusion_matrix def to_labels(pos_probs, threshold): return (pos_probs >= threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list,", "score. \"\"\" try: # define thresholds thresholds = np.arange(0, 1, 0.0001) # evaluate", "tpr, _ = roc_curve(test_set, prediction_proba) auc_score = roc_auc_score(test_set, prediction_proba) plot_roc_curve(auc_score, fpr, tpr) elif", "elif plot=='precision-recall': precision, recall, thresholds = precision_recall_curve(test_set, prediction_proba) auc_score = auc(recall, precision) no_skill", "macro F1-Score=%.5f' % (thresholds[ix], scores[ix])) return thresholds[ix] except Exception as error: raise Exception('Caught", "'mcc':mcc, 'confusion_matrix': cm, 'classification_report':classification_report(test_set, predictions, target_names=labels, output_dict=True)} except Exception as error: raise Exception('Caught", "Returns the value maximizes macro f1 score. \"\"\" try: # define thresholds thresholds", "locate the index of the largest f score ix = np.argmax(fscore) print('PR-curve threshold=%f,", "threshold).astype('int') def get_cut_off_threshold_from_precision_recall(precision:list, recall:list, thresholds:list)->int: try: # convert to f score fscore =", "get_cut_off_threshold_through_iteration(prediction_proba, test_set) predictions = prediction_proba>threshold cr = classification_report(test_set, predictions, target_names=labels) cm = confusion_matrix(test_set," ]
[ "Looping 2.1.1: Get the best neighbor 2.1.2: Select the best, between the current", "\"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution for the", "the algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of", "2: Repeat while Control Parameter >= Minimum Control Parameter 2.1. Internal Looping 2.1.1:", "Calibration Algorithm: --------- 1: Initialize 2: Repeat while Control Parameter >= Minimum Control", "best 2. C / Minimum C Calibration Algorithm: --------- 1: Initialize 2: Repeat", "# ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- def initialize_C_approach1(): return 0, 0", "the best 2. C / Minimum C Calibration Algorithm: --------- 1: Initialize 2:", "of the neighborhood (internally it will call the neighborhood provided to the algorithm)", "class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing with some improvements. Improvements: ------------", "Algorithm: --------- 1: Initialize 2: Repeat while Control Parameter >= Minimum Control Parameter", "Use one of the available approaches to initialize C and Minimum C \"\"\"", "provided to the algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use", "# memory (to avoid lost the best) self._best_solution = None # Search #----------------------------------------------------------------------------------------------", "Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial solution,", "of the available approaches to initialize C and Minimum C \"\"\" pass #", "solution): \"\"\" Get a random neighbor of the neighborhood (internally it will call", "/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic", "function that must follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0 )", "pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial solution, start C", "Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a random neighbor of the neighborhood", "#---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution for the next iteration \"\"\" pass", "Minimum Control Parameter 2.1. Internal Looping 2.1.1: Get the best neighbor 2.1.2: Select", "(to avoid lost the best) self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def search(self):", "\"\"\" Simulated Annealing Constructor parameters: ----------- * neighborhood_function - it is expected a", "*** 3: Return the Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\"", "\"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial solution, start", "/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated", "-*- # ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing", "Author: <NAME> - <EMAIL> - (2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/", "between the current best and current best neighbor 2.1.3: Check stop condition ***", "Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing with", "it will call the neighborhood provided to the algorithm) \"\"\" pass # Constructor", "Implementation of Simulated Annealing with some improvements. Improvements: ------------ 1. Memory - avoiding", "_get_random_neighbor(self, solution): \"\"\" Get a random neighbor of the neighborhood (internally it will", "Intelligence for Optimization Author: <NAME> - <EMAIL> - (2019) version L4.0 \"\"\" #", "parameters: ----------- * neighborhood_function - it is expected a function that must follow", "best neighbor 2.1.3: Check stop condition *** 2.2. Update C (Control Parameter) 2.3:", "- it is expected a function that must follow the signature: <<neighborhood_function>>( solution,", "None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm:", "_initialize(self): \"\"\" Initialize the initial solution, start C and Minimum C \"\"\" pass", "Constructor parameters: ----------- * neighborhood_function - it is expected a function that must", "self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback # memory (to avoid", "2.1. Internal Looping 2.1.1: Get the best neighbor 2.1.2: Select the best, between", "lost the best) self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated", "Parameter 2.1. Internal Looping 2.1.1: Get the best neighbor 2.1.2: Select the best,", "utf-8 -*- # ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated", "Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing", "E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing:", "iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a random", "1. Memory - avoiding to lose the best 2. C / Minimum C", ") where: - <neighborhood_function> it is the name of the neighborhood function implemented", "- (2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D", "to lose the best 2. C / Minimum C Calibration Algorithm: --------- 1:", "def __init__(self, problem_instance, neighborhood_function, feedback = None, config = {}): \"\"\" Simulated Annealing", "problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback # memory", "# ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing ─────────────────────────────────────────────────────────────────────────", "Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm: 1: Initialize", "def _initialize_C(self): \"\"\" Use one of the available approaches to initialize C and", "class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization Author: <NAME> -", "_initialize_C(self): \"\"\" Use one of the available approaches to initialize C and Minimum", "neighborhood provided to the algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\"", "the neighborhood provided to the algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self):", "\"\"\" Initialize the initial solution, start C and Minimum C \"\"\" pass #", "stop condition *** 2.2. Update C (Control Parameter) 2.3: Check stop condition ***", "stop condition *** 3: Return the Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def", "2. C / Minimum C Calibration Algorithm: --------- 1: Initialize 2: Repeat while", "Annealing Search Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat while Control Parameter >=", "best and current best neighbor 2.1.3: Check stop condition *** 2.2. Update C", "C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- def initialize_C_approach1():", "the solution for the next iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self,", "condition *** 3: Return the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance,", "some improvements. Improvements: ------------ 1. Memory - avoiding to lose the best 2.", "the best) self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing", "Parameter) 2.3: Check stop condition *** 3: Return the Solution \"\"\" pass #", "Update C (Control Parameter) 2.3: Check stop condition *** 3: Return the Solution", "= neighborhood_function self._feedback = feedback # memory (to avoid lost the best) self._best_solution", "config = {}): \"\"\" Simulated Annealing Constructor parameters: ----------- * neighborhood_function - it", "*** 3: Return the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function,", "neighborhood_function, feedback = None, config = {}): \"\"\" Simulated Annealing Constructor parameters: -----------", "Improvements: ------------ 1. Memory - avoiding to lose the best 2. C /", "Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for", "current best neighbor 2.1.3: Check stop condition *** 2.2. Update C (Control Parameter)", "with some improvements. Improvements: ------------ 1. Memory - avoiding to lose the best", "the best, between the current best and current best neighbor 2.1.3: Check stop", "# /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\"", "\"\"\" Select the solution for the next iteration \"\"\" pass # Constructor #----------------------------------------------------------------------------------------------", "Search Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat while Control Parameter >= Minimum", "the initial solution, start C and Minimum C \"\"\" pass # Constructor #----------------------------------------------------------------------------------------------", "def _initialize(self): \"\"\" Initialize the initial solution, start C and Minimum C \"\"\"", "coding: utf-8 -*- # ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class", "-*- coding: utf-8 -*- # ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶", "\"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback = None, config =", "Control Parameter 2.1. Internal Looping 2.1.1: Get the best neighbor 2.1.2: Select the", "signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0 ) where: - <neighborhood_function> it is", "neighborhood (internally it will call the neighborhood provided to the algorithm) \"\"\" pass", "Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization Author: <NAME> - <EMAIL> -", "(internally it will call the neighborhood provided to the algorithm) \"\"\" pass #", "# C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing", "#---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a random neighbor of the neighborhood (internally", "L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/", "# Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial solution, start C and", "the neighborhood (internally it will call the neighborhood provided to the algorithm) \"\"\"", "C / Minimum C Calibration Algorithm: --------- 1: Initialize 2: Repeat while Control", "\"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- def initialize_C_approach1(): return", "function implemented for the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback", "Repeat while Control Parameter >= Minimum Control Parameter 2.1. Internal Looping 2.1.1: Get", "is the name of the neighborhood function implemented for the problem_instance \"\"\" self._problem_instance", "<reponame>DavidSilva98/dssgsummit2020-challenge # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ----------------------------------", "Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat while Control Parameter >= Minimum Control", "#---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of the available approaches to initialize C", "feedback # memory (to avoid lost the best) self._best_solution = None # Search", "the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback = None,", "------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO", "= {}): \"\"\" Simulated Annealing Constructor parameters: ----------- * neighborhood_function - it is", "------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- #", "initial solution, start C and Minimum C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def", "# Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm: 1:", "(Control Parameter) 2.3: Check stop condition *** 3: Return the Solution \"\"\" pass", "------------ 1. Memory - avoiding to lose the best 2. C / Minimum", "Parameter) 2.3: Check stop condition *** 3: Return the Solution \"\"\" # Constructor", "#---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial solution, start C and Minimum C", "Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial solution, start C and Minimum", "the neighborhood function implemented for the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors =", "Classic Implementation of Simulated Annealing with some improvements. Improvements: ------------ 1. Memory -", "for the next iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\"", "pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution for the next", "# Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback = None, config = {}):", "one of the available approaches to initialize C and Minimum C \"\"\" pass", "avoiding to lose the best 2. C / Minimum C Calibration Algorithm: ---------", "best neighbor 2.1.2: Select the best, between the current best and current best", "condition *** 2.2. Update C (Control Parameter) 2.3: Check stop condition *** 3:", "a random neighbor of the neighborhood (internally it will call the neighborhood provided", "it is expected a function that must follow the signature: <<neighborhood_function>>( solution, problem,", "Return the Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the", "call the neighborhood provided to the algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def", "C and Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing #", "the current best and current best neighbor 2.1.3: Check stop condition *** 2.2.", "random neighbor of the neighborhood (internally it will call the neighborhood provided to", "next iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a", "# Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated", "2.1.1: Get the best neighbor 2.1.2: Select the best, between the current best", "approaches to initialize C and Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class:", "Minimum C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution", "*** 2.2. Update C (Control Parameter) 2.3: Check stop condition *** 3: Return", "follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0 ) where: - <neighborhood_function>", "# Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of the available approaches to", "# ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing with some improvements.", "neighborhood_function - it is expected a function that must follow the signature: <<neighborhood_function>>(", "3: Return the Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize", "name of the neighborhood function implemented for the problem_instance \"\"\" self._problem_instance = problem_instance", "None, config = {}): \"\"\" Simulated Annealing Constructor parameters: ----------- * neighborhood_function -", "and Minimum C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the", "start C and Minimum C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\"", "Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- def", "the best neighbor 2.1.2: Select the best, between the current best and current", "2.3: Check stop condition *** 3: Return the Solution \"\"\" # Constructor #----------------------------------------------------------------------------------------------", "= None, config = {}): \"\"\" Simulated Annealing Constructor parameters: ----------- * neighborhood_function", "= feedback # memory (to avoid lost the best) self._best_solution = None #", "solution for the next iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution):", "Return the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback =", "- <neighborhood_function> it is the name of the neighborhood function implemented for the", "memory (to avoid lost the best) self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def", "solution, start C and Minimum C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self):", "neighbor 2.1.2: Select the best, between the current best and current best neighbor", "{}): \"\"\" Simulated Annealing Constructor parameters: ----------- * neighborhood_function - it is expected", "__init__(self, problem_instance, neighborhood_function, feedback = None, config = {}): \"\"\" Simulated Annealing Constructor", "Check stop condition *** 2.2. Update C (Control Parameter) 2.3: Check stop condition", "avoid lost the best) self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\"", "Select the best, between the current best and current best neighbor 2.1.3: Check", "= None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search Method ----------------------------------", "solution, problem, neighborhood_size = 0 ) where: - <neighborhood_function> it is the name", "algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of the", "/ Minimum C Calibration Algorithm: --------- 1: Initialize 2: Repeat while Control Parameter", "2.1.2: Select the best, between the current best and current best neighbor 2.1.3:", "\"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback # memory (to", "pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a random neighbor of", "Computation Intelligence for Optimization Author: <NAME> - <EMAIL> - (2019) version L4.0 \"\"\"", "while Control Parameter >= Minimum Control Parameter 2.1. Internal Looping 2.1.1: Get the", "the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback #", "Simulated Annealing with some improvements. Improvements: ------------ 1. Memory - avoiding to lose", "C (Control Parameter) 2.3: Check stop condition *** 3: Return the Solution \"\"\"", "Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution for the next iteration \"\"\"", "the Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self): \"\"\" Initialize the initial", "for the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback", "to the algorithm) \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one", "#---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm: 1: Initialize 2:", "Control Parameter >= Minimum Control Parameter 2.1. Internal Looping 2.1.1: Get the best", "and current best neighbor 2.1.3: Check stop condition *** 2.2. Update C (Control", "D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class", "Simulated Annealing Search Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat while Control Parameter", "Check stop condition *** 3: Return the Solution \"\"\" pass # Constructor #----------------------------------------------------------------------------------------------", "Annealing with some improvements. Improvements: ------------ 1. Memory - avoiding to lose the", "where: - <neighborhood_function> it is the name of the neighborhood function implemented for", "\"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO -", "----------- * neighborhood_function - it is expected a function that must follow the", "neighborhood function implemented for the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function", "best) self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search", "Initialize 2: Repeat while Control Parameter >= Minimum Control Parameter 2.1. Internal Looping", "* neighborhood_function - it is expected a function that must follow the signature:", "condition *** 3: Return the Solution \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize(self):", "Minimum C Calibration Algorithm: --------- 1: Initialize 2: Repeat while Control Parameter >=", "Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization Author:", "───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization Author: <NAME> - <EMAIL> - (2019)", "---------------------------------- Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization", "def _get_random_neighbor(self, solution): \"\"\" Get a random neighbor of the neighborhood (internally it", "stop condition *** 3: Return the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self,", "= 0 ) where: - <neighborhood_function> it is the name of the neighborhood", "self._get_neighbors = neighborhood_function self._feedback = feedback # memory (to avoid lost the best)", "Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing with some", "2.3: Check stop condition *** 3: Return the Solution \"\"\" pass # Constructor", "C Calibration Algorithm: --------- 1: Initialize 2: Repeat while Control Parameter >= Minimum", "expected a function that must follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size =", "# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------------------------- \"\"\" Simulated Annealing Meta-Heuristic ---------------------------------- Content:", "Initialize the initial solution, start C and Minimum C \"\"\" pass # Constructor", "problem_instance, neighborhood_function, feedback = None, config = {}): \"\"\" Simulated Annealing Constructor parameters:", "neighborhood_function self._feedback = feedback # memory (to avoid lost the best) self._best_solution =", "# ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation", "self._feedback = feedback # memory (to avoid lost the best) self._best_solution = None", "SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing with some improvements. Improvements: ------------ 1.", "Select the solution for the next iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def", "pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of the available approaches", "self._best_solution = None # Search #---------------------------------------------------------------------------------------------- def search(self): \"\"\" Simulated Annealing Search Method", "Get the best neighbor 2.1.2: Select the best, between the current best and", "------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of Simulated Annealing with some improvements. Improvements:", "- avoiding to lose the best 2. C / Minimum C Calibration Algorithm:", "improvements. Improvements: ------------ 1. Memory - avoiding to lose the best 2. C", "the signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0 ) where: - <neighborhood_function> it", "---------------------------------- Algorithm: 1: Initialize 2: Repeat while Control Parameter >= Minimum Control Parameter", "search(self): \"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat while", "the next iteration \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get", "neighborhood_size = 0 ) where: - <neighborhood_function> it is the name of the", "- <EMAIL> - (2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C", "2.1.3: Check stop condition *** 2.2. Update C (Control Parameter) 2.3: Check stop", "\"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a random neighbor", "\"\"\" Use one of the available approaches to initialize C and Minimum C", "def _select(self): \"\"\" Select the solution for the next iteration \"\"\" pass #", "current best and current best neighbor 2.1.3: Check stop condition *** 2.2. Update", "feedback = None, config = {}): \"\"\" Simulated Annealing Constructor parameters: ----------- *", "\"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat while Control", "# ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # -------------------------------------------------------------------------------------------------", "3: Return the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback", "------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- class SimulatedAnnealing: \"\"\" Classic Implementation of", "# Constructor #---------------------------------------------------------------------------------------------- def _get_random_neighbor(self, solution): \"\"\" Get a random neighbor of the", "# /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class:", "available approaches to initialize C and Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- #", "<EMAIL> - (2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O", "(2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E", "Annealing Constructor parameters: ----------- * neighborhood_function - it is expected a function that", "it is the name of the neighborhood function implemented for the problem_instance \"\"\"", "best, between the current best and current best neighbor 2.1.3: Check stop condition", "that must follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0 ) where:", "Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of the available approaches to initialize", "of the neighborhood function implemented for the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors", "lose the best 2. C / Minimum C Calibration Algorithm: --------- 1: Initialize", "version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E #", "problem, neighborhood_size = 0 ) where: - <neighborhood_function> it is the name of", "2.2. Update C (Control Parameter) 2.3: Check stop condition *** 3: Return the", "O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # -------------------------------------------------------------------------------------------------", "\"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _initialize_C(self): \"\"\" Use one of the available", "neighbor 2.1.3: Check stop condition *** 2.2. Update C (Control Parameter) 2.3: Check", "(Control Parameter) 2.3: Check stop condition *** 3: Return the Solution \"\"\" #", "▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization Author: <NAME>", "CIFO - Computation Intelligence for Optimization Author: <NAME> - <EMAIL> - (2019) version", "C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution for", "1: Initialize 2: Repeat while Control Parameter >= Minimum Control Parameter 2.1. Internal", "Simulated Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation", "\"\"\" Classic Implementation of Simulated Annealing with some improvements. Improvements: ------------ 1. Memory", "the name of the neighborhood function implemented for the problem_instance \"\"\" self._problem_instance =", "# Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select the solution for the next iteration", "and Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # -------------------------------------------------------------------------------------------------", "Memory - avoiding to lose the best 2. C / Minimum C Calibration", "pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing # ------------------------------------------------------------------------------------------------- def initialize_C_approach1(): return 0,", "for Optimization Author: <NAME> - <EMAIL> - (2019) version L4.0 \"\"\" # -------------------------------------------------------------------------------------------------", "Internal Looping 2.1.1: Get the best neighbor 2.1.2: Select the best, between the", "Check stop condition *** 3: Return the Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def", "Get a random neighbor of the neighborhood (internally it will call the neighborhood", "Simulated Annealing Constructor parameters: ----------- * neighborhood_function - it is expected a function", "<NAME> - <EMAIL> - (2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ #", "0 ) where: - <neighborhood_function> it is the name of the neighborhood function", "Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence for Optimization Author: <NAME> - <EMAIL>", "of Simulated Annealing with some improvements. Improvements: ------------ 1. Memory - avoiding to", "the available approaches to initialize C and Minimum C \"\"\" pass # -------------------------------------------------------------------------------------------------", "--------- 1: Initialize 2: Repeat while Control Parameter >= Minimum Control Parameter 2.1.", "must follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0 ) where: -", "is expected a function that must follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size", "Optimization Author: <NAME> - <EMAIL> - (2019) version L4.0 \"\"\" # ------------------------------------------------------------------------------------------------- #", "a function that must follow the signature: <<neighborhood_function>>( solution, problem, neighborhood_size = 0", "neighbor of the neighborhood (internally it will call the neighborhood provided to the", "\"\"\" # ------------------------------------------------------------------------------------------------- # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ #", "= problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback # memory (to avoid lost", "def search(self): \"\"\" Simulated Annealing Search Method ---------------------------------- Algorithm: 1: Initialize 2: Repeat", "C O D E # /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/ # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing #", ">= Minimum Control Parameter 2.1. Internal Looping 2.1.1: Get the best neighbor 2.1.2:", "problem_instance self._get_neighbors = neighborhood_function self._feedback = feedback # memory (to avoid lost the", "- Computation Intelligence for Optimization Author: <NAME> - <EMAIL> - (2019) version L4.0", "initialize C and Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated Annealing", "#---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback = None, config = {}): \"\"\" Simulated", "Parameter >= Minimum Control Parameter 2.1. Internal Looping 2.1.1: Get the best neighbor", "will call the neighborhood provided to the algorithm) \"\"\" pass # Constructor #----------------------------------------------------------------------------------------------", "Algorithm: 1: Initialize 2: Repeat while Control Parameter >= Minimum Control Parameter 2.1.", "<neighborhood_function> it is the name of the neighborhood function implemented for the problem_instance", "_select(self): \"\"\" Select the solution for the next iteration \"\"\" pass # Constructor", "implemented for the problem_instance \"\"\" self._problem_instance = problem_instance self._get_neighbors = neighborhood_function self._feedback =", "\"\"\" Get a random neighbor of the neighborhood (internally it will call the", "Annealing Meta-Heuristic ---------------------------------- Content: ▶ class Simulated Annealing ───────────────────────────────────────────────────────────────────────── CIFO - Computation Intelligence", "<<neighborhood_function>>( solution, problem, neighborhood_size = 0 ) where: - <neighborhood_function> it is the", "C and Minimum C \"\"\" pass # Constructor #---------------------------------------------------------------------------------------------- def _select(self): \"\"\" Select", "to initialize C and Minimum C \"\"\" pass # ------------------------------------------------------------------------------------------------- # Class: Simulated", "Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback = None, config = {}): \"\"\"", "Solution \"\"\" # Constructor #---------------------------------------------------------------------------------------------- def __init__(self, problem_instance, neighborhood_function, feedback = None, config" ]
[ "gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image gv_image = gv_data.to(gv.Image)", "cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small", "coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is", "dpi=100,bbox_inches='tight') # close the figure to avoid taking CPU memory plt.close() ################################################################################################ #", "each single dataset and match it with the full grid # Step 1>", "# extract data from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the", "the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) #", "(\"the full grid\") # so that we can combine the data from different", "CPU memory plt.close() ################################################################################################ # build a function to generatet the bar for", "from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate", "select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read daily data", "out all the sampling dates return sampling_dates # list all the dates Suez_days", "to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon))", "lats and lons in the domain def expand_grid(lat,lon): '''list all combinations of lats", "from 1D in the dataframe to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty", "oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return", "coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is complicated to save out the results", "it with the full grid # Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output')", "as crs import geopandas as gpd # read shape file (Global high resolution", "NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the full domain grids NO2_data", "time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file) #", "[] lon_max = [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min", "for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the", "Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week] # convert the data", "format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data,", "to read daily data or weekly data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\"", "print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match with the \"full grid\" Oversampled_NO2_week =", "consuming when we need to produce many figures import matplotlib.pyplot as plt import", "geoviews version, some commands may not work in a wrong version # this", "define the map domain, provide the min and max of the values on", "Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day] # convert the data", "match with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week", "Step 2> feed the oversampled data into this data cleaning routine # read", "coverage may not be consistent on different days or during different weeks #", "data to the xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in", "and lons: use (min,max+1/2 resolutions, resolution) to keep the max value in Python", "close the figure to avoid taking CPU memory plt.close() ################################################################################################ # check again", "and combine with GeoViews ''' ##################################################################################################################### # build a function to read oversampled", "maps together in time series # load GeoViews package import geoviews as gv", "data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"),", "lat_max = max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max) # check the full", "coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') #", "add the variable name daily_data = [data.rename('NO2') for data in daily_data] # add", "names # weekly maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for", "xarray as xr ''' Note on this Suez Canal blockage Blockage period: 23-29", "xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr =", "space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array, define", "Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True])", "time dimension to the data for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i]", "or during different weeks # read all the data from the weekly results", "avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build", "in lat for B in lon] test = np.array(test) test_lat = test[:,0] test_lon", "print out all the sampling dates return sampling_dates # list all the dates", "= np.array(test) test_lat = test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon':", "from NOAA # Think about how to do this with geopandas ##################################################################################################################### #####################################################################################################################", "test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid #", "as the \"pd.merge\" step later will require the values of \"keys\" to be", "for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small", "out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid taking CPU memory plt.close()", "lat_min = min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max) #", "data # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i", "in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data together", "all the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x:", "\"full grid\" by listing the full combinations of lats and lons in the", "[] lat_max = [] lon_min = [] lon_max = [] for i in", "above and the resolution, we can create a consistent domain (\"the full grid\")", "day 8-14 # plot weekly data # plot over the big domain [lon_min,lon_max,lat_min,lat_max]", "# so that we can combine the data from different days/weeks together #", "now, the default coastline from GeoViews is used # If you can crop", "# save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid taking CPU", "in the same way as above, but remove the plot rather than the", "but remove the plot rather than the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys", "# set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0])", "ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid taking", "sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled", "So here we use the list comprehensions to process multiple files ################# #", "on different days or during different weeks # read all the data from", "date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates = [] for", "written under version 1.9.1 print(gv.__version__) # there are two backends ('bokeh', 'matplotlib') for", "avoid taking CPU memory plt.close() ################################################################################################ # check again the data for plotting", "read all the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda", "lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min) lon_max", "= input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the", "and match with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily]", "look at the results # avoid setting \"%matplotlib inline\" as it is time", "March 2021 Data download period: 5 January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max):", "corresponding output file names # weekly maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_')", "[lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the", "gv import geoviews.feature as gf import cartopy.crs as crs # it is important", "# daily maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number", "just round the floats created by Python to be safe # as the", "before, during and after the blockage, get maps and time serires plot Second", "there is no need to make a small map # but if you", "sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match with the", "gv_image = gv_data.to(gv.Image) # decide features of the output figure gv_image_out = gv_image.opts(cmap='jet',", "a legend to save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a", "as plt import cartopy.crs as crs import geopandas as gpd # read shape", "True]) for data in Oversampled_NO2_day] # convert the data to the xarray format", "the geoviews image gv_image = gv_data.to(gv.Image) # decide features of the output figure", "inline\" as it is time consuming when we need to produce many figures", "Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\")", "will use \"bokeh\" for interactive plots ################################################################################################ # weekly maps # list all", "''' Note on this Suez Canal blockage Blockage period: 23-29 March 2021 Data", "domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ #", "2:1 due to the sampling region fig = plt.figure(figsize=[20,10]) # set the map", "# later we will use \"bokeh\" for interactive plots ################################################################################################ # weekly maps", "timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates", "lon_max = max(lon_max) # check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) #", "fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid taking CPU memory plt.close() ################################################################################################", "decide features of the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500)", "2021 Data download period: 5 January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50", "combine with GeoViews ''' ##################################################################################################################### # build a function to read oversampled TROPOMI", "NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables", "= [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week] ################# # daily data", "interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the default coastline", "check again the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding", "will require the values of \"keys\" to be excatly the same Res =", "xr ''' Note on this Suez Canal blockage Blockage period: 23-29 March 2021", "# check the results NO2_week_xr_combined # output the plots # first move to", "* gf.coastline # save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps')", "data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week] #", "print(Oversampled_NO2_file) # Step 2> feed the oversampled data into this data cleaning routine", "+ timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling dates return sampling_dates # list", "with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day =", "Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data", "maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks]", "width=800, height=500) * gf.coastline # save out the interactive map renderer = gv.renderer('bokeh')", "own shapefile, you should be able to use high resolution shorelines from NOAA", "For now, the default coastline from GeoViews is used # If you can", "domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a function", "remove the plot rather than the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys =", "the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') #", "lons: use (min,max+1/2 resolutions, resolution) to keep the max value in Python #", "[data.rename('NO2') for data in daily_data] # add a time dimension to the data", "# check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension", "than the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' :", "# read oversampled data and match with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file)", "NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check", "time serires plot Second test: get daily maps and combine with GeoViews '''", "this Suez Canal blockage Blockage period: 23-29 March 2021 Data download period: 5", "map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map im", "# close the figure to avoid taking CPU memory plt.close() ################################################################################################ # build", "file in Oversampled_NO2_files] # use all the data ever sampled to decide the", "larger domain (Suez and its surrounding + Mediterranean Sea) import os import glob", "the data for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') #", "Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small", "the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True])", "plots ################################################################################################ # weekly maps # list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16']", "if you have to reduce the file size, you can subset over the", "lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max)", "use high resolution shorelines from NOAA # Think about how to do this", "figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the same way as", "NO2_day_xr_combined # output the plots # first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures')", "grid # Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time", "commands may not work in a wrong version # this script is written", "function to generatet the bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw", "xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count,", "test: sample weekly data before, during and after the blockage, get maps and", "with the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True,", "important to check your geoviews version, some commands may not work in a", "Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True,", "NO2_day_xr.copy() # add the variable name daily_data = [data.rename('NO2') for data in daily_data]", "the oversampled data into this data cleaning routine # read oversampled NO2 data", "during and after the blockage, get maps and time serires plot Second test:", "# Now we can read each single dataset and match it with the", "the results NO2_day_xr_combined # output the plots # first move to the output", "same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3)", "# extract data from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the", "copy first weekly_data = NO2_week_xr.copy() # add the variable name weekly_data = [data.rename('NO2')", "to the xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week]", "a function to generatet the bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): '''", "gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image gv_image", "the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label}", "the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above and", "for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in", "for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week]", "file for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns =", "file (Global high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\"", "variable name daily_data = [data.rename('NO2') for data in daily_data] # add a time", "the figure size, the aspect ratio is set to be 2:1 due to", "shape file (Global high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full", "Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data", "= ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial coverage may not be consistent", "data before, during and after the blockage, get maps and time serires plot", "def expand_grid(lat,lon): '''list all combinations of lats and lons using expand_grid(lat,lon)''' test =", "shapefile, you should be able to use high resolution shorelines from NOAA #", "= [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for", "with GeoViews ''' ##################################################################################################################### # build a function to read oversampled TROPOMI NO2", "for the GeoViews # later we will use \"bokeh\" for interactive plots ################################################################################################", "data in weekly_data] # check the results NO2_week_xr_combined # output the plots #", "expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can read each single dataset and match", "# Step 2> feed the oversampled data into this data cleaning routine #", "= [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in", "you can crop and create your own shapefile, you should be able to", "to read oversampled TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output", "Python # just round the floats created by Python to be safe #", "# use the data to generate the geoviews image gv_image = gv_data.to(gv.Image) #", "print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays from daily results # make a", "range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined", "np.round(domain_lon,3) # build a function to create a \"full grid\" by listing the", "a xarray data array, define the map domain, provide the min and max", "comprehensions to process multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the", "later we will use \"bokeh\" for interactive plots ################################################################################################ # weekly maps #", "together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom in and change maps, so", "quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array, define the map domain, provide the", "################################################################################################ # weekly maps # list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\")", "color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot", "# weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_weekly", "import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date -", "NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them", "NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)])", "= [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for", "Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays", "full grid\") # so that we can combine the data from different days/weeks", "colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} #", "data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read daily data or weekly data", "max value in Python # just round the floats created by Python to", "NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled TROPOMI", "and the resolution, we can create a consistent domain (\"the full grid\") #", "domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data] # check", "# weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data] # check the", "match it with the full grid # Step 1> select the oversampled data", "in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during", "time series # load GeoViews package import geoviews as gv import geoviews.feature as", "be safe # as the \"pd.merge\" step later will require the values of", "blockage # When downloading the data, look at a larger domain (Suez and", "plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)):", "taking CPU memory plt.close() ################################################################################################ # check again the data for plotting print(\"weekly", "the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left',", "i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max)", "= df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial coverage may", "lon_min = [] lon_max = [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min())", "memory plt.close() ################################################################################################ # build a function to generatet the bar for the", "memory plt.close() ################################################################################################ # check again the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily", "gv.extension('bokeh') # extract data from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use", "the data for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') #", "the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined # output", "the end from datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8]))", "extract data from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data", "over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big'))", "may not work in a wrong version # this script is written under", "A in lat for B in lon] test = np.array(test) test_lat = test[:,0]", "NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom", "12 # day 8-14 # plot weekly data # plot over the big", "NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) #", "image gv_image = gv_data.to(gv.Image) # decide features of the output figure gv_image_out =", "to keep the max value in Python # just round the floats created", "bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily", "input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile plt.delaxes(fig.axes[1])", "in lon] test = np.array(test) test_lat = test[:,0] test_lon = test[:,1] full_grid =", "during the blockage # week 12 # day 8-14 # plot weekly data", "plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the same way as above, but remove", "Canal blockage # When downloading the data, look at a larger domain (Suez", "[] lon_min = [] lon_max = [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max())", "grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for", "the start and the end from datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8]))", "[26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at the", "remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') #", "xr.concat(NO2_week_xr,'week') # you can zoom in and change maps, so normally there is", "# convert the data to the xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon))", "[6,7,8,9,10,11,12,13,14] First test: sample weekly data before, during and after the blockage, get", "NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray", "xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image", "\"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can read each", "so that we can combine the data from different days/weeks together # first", "list all the lats and lons: use (min,max+1/2 resolutions, resolution) to keep the", "# build a function to generatet the bar for the figures above def", "domain_lat),('lon', domain_lon)]) # but it is complicated to save out the results one", "we can create a consistent domain (\"the full grid\") # so that we", "generate corresponding output file names # weekly maps Suez_weeks = list(range(1,17)) Suez_weeks =", "value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size plt.rcParams.update({'font.size':25})", "input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot", "data to the xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in", "the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom in and change", "'pad' : 0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain)", "the spatial coverage may not be consistent on different days or during different", "as above, but remove the plot rather than the colorbar. ''' fig =", "are two backends ('bokeh', 'matplotlib') for the GeoViews # later we will use", "for data in NO2_day] ################################################################################################ # Start making maps to have a quick", "have a quick look at the results # avoid setting \"%matplotlib inline\" as", "= expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can read each single dataset and", "one for multiple days or weeks ################################################################################################ ################################################################################################ # So here we use", "################################################################################################ # daily maps # list all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI", "file size, you can subset over the small domain # weekly_data = [data.sel(lat=slice(10,35),lon", "over the small domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in", "domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a function to create a", "TROPOMI files within the start date ('yyyymmdd') and end date ('yyyymmdd')''' # list", "= date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates = []", "str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures')", "you can zoom in and change maps, so normally there is no need", "value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove", "so normally there is no need to make a small map # but", "ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close", "NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined # output the plots #", "lon_min = min(lon_min) lon_max = max(lon_max) # check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max)", "for multiple days or weeks ################################################################################################ ################################################################################################ # So here we use the", "print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for", "and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read", "oversampled data into this data cleaning routine # read oversampled NO2 data NO2_data", "period: 5 January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows", "the results # avoid setting \"%matplotlib inline\" as it is time consuming when", "sampling region fig = plt.figure(figsize=[20,10]) # set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection", "+ Mediterranean Sea) import os import glob import numpy as np import pandas", "[read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use all the data ever sampled to", "domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################ # Start making maps to have", "and change maps, so normally there is no need to make a small", "January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data", "Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output", "the GeoViews # later we will use \"bokeh\" for interactive plots ################################################################################################ #", "2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First test:", "need to produce many figures import matplotlib.pyplot as plt import cartopy.crs as crs", "small map # but if you have to reduce the file size, you", "you can subset over the small domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60))", "outputfile name. ''' # set the figure size, the aspect ratio is set", "map domain, provide the min and max of the values on map. Provide", "for A in lat for B in lon] test = np.array(test) test_lat =", "'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file) # Step 2>", "full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) #", "# load GeoViews package import geoviews as gv import geoviews.feature as gf import", "= plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the map", "round the floats created by Python to be safe # as the \"pd.merge\"", "= [data.rename('NO2') for data in weekly_data] # add a time dimension to the", "floats created by Python to be safe # as the \"pd.merge\" step later", "again the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output", "to create a \"full grid\" by listing the full combinations of lats and", "output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline # save", "to the sampling region fig = plt.figure(figsize=[20,10]) # set the map projection and", "combine the xarray data arrays from weekly results # make a copy first", "0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe", "# plot the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry,", "save out the results one by one for multiple days or weeks ################################################################################################", "# combine the data with the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon'])", "= [str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple", "= [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain", "= gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline # save out the interactive", "file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day =", "but if you have to reduce the file size, you can subset over", "# remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight')", "gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline # save out the interactive map", "Now we can read each single dataset and match it with the full", "import Dataset import xarray as xr ''' Note on this Suez Canal blockage", "it is time consuming when we need to produce many figures import matplotlib.pyplot", "= plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set", "the max value in Python # just round the floats created by Python", "and max of the values on map. Provide a outputfile name. ''' #", "# save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For", "i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to combine the maps", "gf import cartopy.crs as crs # it is important to check your geoviews", "dimension to the data for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] =", "domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is complicated to", "figure to avoid taking CPU memory plt.close() ################################################################################################ # check again the data", "the Suez Canal blockage # When downloading the data, look at a larger", "for B in lon] test = np.array(test) test_lat = test[:,0] test_lon = test[:,1]", "= [] lon_min = [] lon_max = [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min())", "NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df #####################################################################################################################", "= list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays from", "file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week =", "that we can combine the data from different days/weeks together # first list", "maps and time serires plot Second test: get daily maps and combine with", "fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the", "to avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ #", "# select the files and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x:", "when we need to produce many figures import matplotlib.pyplot as plt import cartopy.crs", "for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in", "data arrays from weekly results # make a copy first weekly_data = NO2_week_xr.copy()", "the variable name daily_data = [data.rename('NO2') for data in daily_data] # add a", "crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name,", "domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on map im", "= [read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use all the data ever sampled", "way as above, but remove the plot rather than the colorbar. ''' fig", "weekly_data] # add a time dimension to the data for i in range(len(NO2_week_xr)):", "daily maps # list all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within", "can zoom in and change maps, so normally there is no need to", "consistent on different days or during different weeks # read all the data", "= [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to", "on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in", "create a consistent domain (\"the full grid\") # so that we can combine", "matplotlib.pyplot as plt import cartopy.crs as crs import geopandas as gpd # read", "cartopy.crs as crs # it is important to check your geoviews version, some", "df ##################################################################################################################### # the spatial coverage may not be consistent on different days", "i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data", "lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min) lon_max =", "data cleaning routine # read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine", "ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out", "in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling", "multiple days or weeks ################################################################################################ ################################################################################################ # So here we use the list", "the resolution, we can create a consistent domain (\"the full grid\") # so", "'daily_maps') # For now, the default coastline from GeoViews is used # If", "range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling dates", "in weekly_data] # add a time dimension to the data for i in", "str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29)) Suez_days", "plt import cartopy.crs as crs import geopandas as gpd # read shape file", "the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate the", "Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day] # convert the", "the files and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\")", "TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled", "TROPOMI NO2 responds to the Suez Canal blockage # When downloading the data,", "the list comprehensions to process multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') #", "provide the min and max of the values on map. Provide a outputfile", "plot rather than the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1,", "you have to reduce the file size, you can subset over the small", "range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max) lon_min =", "results # make a copy first weekly_data = NO2_week_xr.copy() # add the variable", "and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read", "(Global high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here", "domain, provide the min and max of the values on map. Provide a", "make a small map # but if you have to reduce the file", "'''list all combinations of lats and lons using expand_grid(lat,lon)''' test = [(A,B) for", "# first list all the lats and lons: use (min,max+1/2 resolutions, resolution) to", "read shape file (Global high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use", "return sampling_dates # list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days))", "domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is complicated", "the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to enable interactive map", "delta = end_date - start_date sampling_dates = [] for i in range(delta.days +", "in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day] # convert", "days/weeks together # first list all the lats and lons: use (min,max+1/2 resolutions,", "[lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color", "the blockage, get maps and time serires plot Second test: get daily maps", "[lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use", "CPU memory plt.close() ################################################################################################ # check again the data for plotting print(\"weekly data:\",len(NO2_week_xr))", "NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting NO2_xarray = xr.DataArray(NO2,", "blockage Blockage period: 23-29 March 2021 Data download period: 5 January - 26", "grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can read each single", "the min and max of the values on map. Provide a outputfile name.", "here to avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################", "['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays from weekly results # make", "True]) # reshape the variables from 1D in the dataframe to the map", "= [] lat_max = [] lon_min = [] lon_max = [] for i", "ever sampled to decide the max dimension lat_min = [] lat_max = []", "for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day]", "5 January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for", "the max dimension lat_min = [] lat_max = [] lon_min = [] lon_max", "for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max =", "responds to the Suez Canal blockage # When downloading the data, look at", "is set to be 2:1 due to the sampling region fig = plt.figure(figsize=[20,10])", "import geopandas as gpd # read shape file (Global high resolution shoreline database", "clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline # save out the interactive map renderer", "################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically", "weekly_data = [data.rename('NO2') for data in weekly_data] # add a time dimension to", "im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove", "downloading the data, look at a larger domain (Suez and its surrounding +", "be able to use high resolution shorelines from NOAA # Think about how", "the files and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\")", "os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file", "the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline #", "plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the map projection:", "# set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) #", "print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above and the resolution, we can create", "figure in the same way as above, but remove the plot rather than", "download period: 5 January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour", "[xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output')", "a outputfile name. ''' # set the figure size, the aspect ratio is", "# it is important to check your geoviews version, some commands may not", "NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined =", "max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max) # check the full dimension print(\"lat_min:\",lat_min)", "TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df", "# you can zoom in and change maps, so normally there is no", "map gv.extension('bokeh') # extract data from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) #", "data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the full domain grids", "multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort", "ascending=[True, True]) for data in Oversampled_NO2_week] # convert the data to the xarray", "check your geoviews version, some commands may not work in a wrong version", "test: get daily maps and combine with GeoViews ''' ##################################################################################################################### # build a", "domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over", "as gf import cartopy.crs as crs # it is important to check your", "backend to enable interactive map gv.extension('bokeh') # extract data from the combined xarray", "gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline # save out the", "# list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") #", "a copy first weekly_data = NO2_week_xr.copy() # add the variable name weekly_data =", "# maps during the blockage # week 12 # day 8-14 # plot", "= xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is complicated to save out", "sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled", "projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map im =", "= np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a function to create a \"full", "big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot", "Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True])", "the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray", "xarray data arrays from weekly results # make a copy first weekly_data =", "variables from 1D in the dataframe to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon))", "data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day]", "gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the default coastline from GeoViews is used", "the results one by one for multiple days or weeks ################################################################################################ ################################################################################################ #", "xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is complicated to save out the", "data in weekly_data] # add a time dimension to the data for i", "for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the", "and lons using expand_grid(lat,lon)''' test = [(A,B) for A in lat for B", "import matplotlib.pyplot as plt import cartopy.crs as crs import geopandas as gpd #", "Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar", "NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to avoid misrepresentation of land and", "list all the dates between the start and the end from datetime import", "# generate the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec.", "plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)):", "zoom in and change maps, so normally there is no need to make", "list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ #", "pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid # create the \"full grid\" domain_grid =", "generate the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\")", "['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial coverage may not be consistent on", "the results NO2_week_xr_combined # output the plots # first move to the output", "results one by one for multiple days or weeks ################################################################################################ ################################################################################################ # So", "# If you can crop and create your own shapefile, you should be", "to check your geoviews version, some commands may not work in a wrong", "above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the same way as above,", "quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to combine the maps together in time", "Mediterranean Sea) import os import glob import numpy as np import pandas as", "dataset and match it with the full grid # Step 1> select the", "domain_lon)]) for data in NO2_day] ################################################################################################ # Start making maps to have a", "results NO2_day_xr_combined # output the plots # first move to the output directory", "= [str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days", "data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom in and change maps,", "''' # set the figure size, the aspect ratio is set to be", "first weekly_data = NO2_week_xr.copy() # add the variable name weekly_data = [data.rename('NO2') for", "values on map. Provide a outputfile name. ''' # set the figure size,", "= xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined # output the plots # first", "version, some commands may not work in a wrong version # this script", "# read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data with", "interactive map gv.extension('bokeh') # extract data from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree())", "list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays from daily", "= xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray =", "os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to enable interactive map gv.extension('bokeh') # extract", "value in Python # just round the floats created by Python to be", "daily maps and combine with GeoViews ''' ##################################################################################################################### # build a function to", "= list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") #", "to enable interactive map gv.extension('bokeh') # extract data from the combined xarray gv_data", "oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use all the data ever", "[data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week] # convert the data to the", "expand_grid(lat,lon)''' test = [(A,B) for A in lat for B in lon] test", "get daily maps and combine with GeoViews ''' ##################################################################################################################### # build a function", "################################################################################################ # check again the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) #", "data from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to", "oversampled data and match with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file", "time dimension to the data for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i]", "extract data from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data", "combine the maps together in time series # load GeoViews package import geoviews", "here we use the list comprehensions to process multiple files ################# # weekly", "no need to make a small map # but if you have to", "xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat',", "os import glob import numpy as np import pandas as pd from netCDF4", "combine the data with the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data", "domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon',", "from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate", "data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined # output the", "name daily_data = [data.rename('NO2') for data in daily_data] # add a time dimension", "require the values of \"keys\" to be excatly the same Res = 0.05", "Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week] ################# #", "quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i", "hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data before, during", "legend to save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray", "= test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid # create the", "maps, so normally there is no need to make a small map #", "sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling dates return sampling_dates #", "date ('yyyymmdd') and end date ('yyyymmdd')''' # list all the dates between the", "over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small'))", "the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the default", "database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to avoid misrepresentation of", "to process multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files", "features of the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) *", "in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################", "def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None)", "Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon", "the figure to avoid taking CPU memory plt.close() ################################################################################################ # check again the", "GeoViews # later we will use \"bokeh\" for interactive plots ################################################################################################ # weekly", "function to read oversampled TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the", "data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\")", "between the start and the end from datetime import date, timedelta start_date =", "as np import pandas as pd from netCDF4 import Dataset import xarray as", "GeoViews package import geoviews as gv import geoviews.feature as gf import cartopy.crs as", "coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat',", "NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables from 1D in the", "dates between the start and the end from datetime import date, timedelta start_date", "# plot daily data # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small =", "the dimension above and the resolution, we can create a consistent domain (\"the", "# day 8-14 # plot weekly data # plot over the big domain", "First test: sample weekly data before, during and after the blockage, get maps", "figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline # save out", "gv.extension('bokeh') # extract data from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use", "full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid # create the \"full grid\"", "= [(A,B) for A in lat for B in lon] test = np.array(test)", "a quick look at the results # avoid setting \"%matplotlib inline\" as it", "= [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in", "= gv_data.to(gv.Image) # decide features of the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2),", "dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above and the resolution,", "################################################################################################ ################################################################################################ # So here we use the list comprehensions to process multiple", "function to create a \"full grid\" by listing the full combinations of lats", "plot the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none')", "# add a time dimension to the data for i in range(len(NO2_day_xr)): NO2_day_xr[i]", "Oversampled_NO2_day] # convert the data to the xarray format for plotting NO2_day =", "and match with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly]", "it is complicated to save out the results one by one for multiple", "for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to combine the", "use \"bokeh\" for interactive plots ################################################################################################ # weekly maps # list all the", "input time to read daily data or weekly data time = 'week_1' Oversampled_NO2_file", "all the data ever sampled to decide the max dimension lat_min = []", "in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data together", "for data in Oversampled_NO2_day] # convert the data to the xarray format for", "read daily data or weekly data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" #", "print(\"lon_max:\",lon_max) # With the dimension above and the resolution, we can create a", "# build a function to read oversampled TROPOMI NO2 as pandas dataframes def", "daily results # make a copy first daily_data = NO2_day_xr.copy() # add the", "# output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage # week", "check the results NO2_day_xr_combined # output the plots # first move to the", "grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for", "\"keys\" to be excatly the same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon", "= [] lon_max = [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max())", "days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays from daily results # make", "data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data before, during and after the", "the xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr", "NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom in and change maps, so normally", "int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use all the", "renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the default coastline from GeoViews", "NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined =", "function to quickly generate maps without a legend to save space on a", "= NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can", "list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily", "the same way as above, but remove the plot rather than the colorbar.", "set to be 2:1 due to the sampling region fig = plt.figure(figsize=[20,10]) #", "the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file", "excatly the same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat", "= min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max) # check", "we use the list comprehensions to process multiple files ################# # weekly data", "in Python # just round the floats created by Python to be safe", "= sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match with", "for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29)) Suez_days =", "numpy as np import pandas as pd from netCDF4 import Dataset import xarray", "np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a function to create", "key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match with the \"full", "NO2 responds to the Suez Canal blockage # When downloading the data, look", "or weekly data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected", "Provide a outputfile name. ''' # set the figure size, the aspect ratio", "small domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data] #", "plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)])", "a function to read oversampled TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read", "world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to quickly generate maps without", "is important to check your geoviews version, some commands may not work in", "list comprehensions to process multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select", "weekly maps # list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine", "is written under version 1.9.1 print(gv.__version__) # there are two backends ('bokeh', 'matplotlib')", "save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily", "# Use GeoViews to combine the maps together in time series # load", "Python to be safe # as the \"pd.merge\" step later will require the", "##################################################################################################################### # the spatial coverage may not be consistent on different days or", "int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match with the \"full grid\" Oversampled_NO2_week", "serires plot Second test: get daily maps and combine with GeoViews ''' #####################################################################################################################", "over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small'))", "# just round the floats created by Python to be safe # as", "of lats and lons in the domain def expand_grid(lat,lon): '''list all combinations of", "output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to enable interactive map gv.extension('bokeh')", "NO2_week_xr_combined # output the plots # first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures')", "tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot over the", "xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined # output the plots # first move", "by Python to be safe # as the \"pd.merge\" step later will require", "plot weekly data # plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50]", "out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps", "map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps # list all", "################################################################################################ # build a function to quickly generate maps without a legend to", "Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number)", "use \"full reolution\" here to avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore", "ascending=[True, True]) for data in Oversampled_NO2_day] # convert the data to the xarray", "# read oversampled data and match with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file)", "Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file) # Step 2> feed", "to use high resolution shorelines from NOAA # Think about how to do", "in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week] #################", "# daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_daily", "in NO2_day] ################################################################################################ # Start making maps to have a quick look at", "map gv.extension('bokeh') # extract data from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) #", "check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above", "(lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly", "# plot weekly data # plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big =", "on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in", "for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day", "and end date ('yyyymmdd')''' # list all the dates between the start and", "generatet the bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure", "23-29 March 2021 Data download period: 5 January - 26 April 2021 Domain", "import cartopy.crs as crs # it is important to check your geoviews version,", "pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial", "reolution\" here to avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\")", "daily_data = [data.rename('NO2') for data in daily_data] # add a time dimension to", "as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled TROPOMI NO2'''", "Draw the figure in the same way as above, but remove the plot", "def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the same way as above, but", "NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting", "oversampled TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for", "the bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in", "by one for multiple days or weeks ################################################################################################ ################################################################################################ # So here we", "data ever sampled to decide the max dimension lat_min = [] lat_max =", "'matplotlib') for the GeoViews # later we will use \"bokeh\" for interactive plots", "# combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined", "plot Second test: get daily maps and combine with GeoViews ''' ##################################################################################################################### #", "files within the start date ('yyyymmdd') and end date ('yyyymmdd')''' # list all", "check the selected data print(Oversampled_NO2_file) # Step 2> feed the oversampled data into", "\"bokeh\" for interactive plots ################################################################################################ # weekly maps # list all the weeks", "for data in weekly_data] # check the results NO2_week_xr_combined # output the plots", "the selected data print(Oversampled_NO2_file) # Step 2> feed the oversampled data into this", "your own shapefile, you should be able to use high resolution shorelines from", "coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################ # Start making maps to", "there are two backends ('bokeh', 'matplotlib') for the GeoViews # later we will", "= 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon =", "dates return sampling_dates # list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of", "# use all the data ever sampled to decide the max dimension lat_min", "create a \"full grid\" by listing the full combinations of lats and lons", "read oversampled data and match with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for", "ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max)", "print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage", "B in lon] test = np.array(test) test_lat = test[:,0] test_lon = test[:,1] full_grid", "backends ('bokeh', 'matplotlib') for the GeoViews # later we will use \"bokeh\" for", "Blockage period: 23-29 March 2021 Data download period: 5 January - 26 April", "the \"pd.merge\" step later will require the values of \"keys\" to be excatly", "= sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files]", "to generate the geoviews image gv_image = gv_data.to(gv.Image) # decide features of the", "start date ('yyyymmdd') and end date ('yyyymmdd')''' # list all the dates between", "\"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon'])", "a time dimension to the data for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i])", "# output the plots # first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') #", "keep the max value in Python # just round the floats created by", "[str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days =", "{'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax =", "height=500) * gf.coastline # save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out,", "used # If you can crop and create your own shapefile, you should", "# this script is written under version 1.9.1 print(gv.__version__) # there are two", "the small domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data]", "= max(lon_max) # check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With", "the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can read", "date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates = [] for i in range(delta.days", "# add the variable name weekly_data = [data.rename('NO2') for data in weekly_data] #", "i in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all the", "Dataset import xarray as xr ''' Note on this Suez Canal blockage Blockage", "test_lat, 'lon': test_lon}) return full_grid # create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon)", "look at a larger domain (Suez and its surrounding + Mediterranean Sea) import", "[pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data", "start and the end from datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date", "timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling dates return sampling_dates # list all", "consistent domain (\"the full grid\") # so that we can combine the data", "combine the data from different days/weeks together # first list all the lats", "data and match with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in", "= list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################", "plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size", "weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_weekly =", "end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates = [] for i", "results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for", "in a wrong version # this script is written under version 1.9.1 print(gv.__version__)", "the figure to avoid taking CPU memory plt.close() ################################################################################################ # build a function", "two backends ('bokeh', 'matplotlib') for the GeoViews # later we will use \"bokeh\"", "data or weekly data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the", "in Oversampled_NO2_day] # convert the data to the xarray format for plotting NO2_day", "files and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") #", "in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort", "use the list comprehensions to process multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output')", "from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to avoid misrepresentation of land", "= np.round(domain_lon,3) # build a function to create a \"full grid\" by listing", "map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar", "weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays from weekly", "interactive map gv.extension('bokeh') # extract data from the combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree())", "is time consuming when we need to produce many figures import matplotlib.pyplot as", "data, look at a larger domain (Suez and its surrounding + Mediterranean Sea)", "''' ##################################################################################################################### # build a function to read oversampled TROPOMI NO2 as pandas", "# use \"full reolution\" here to avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\")", "land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to", "size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight')", "to combine the maps together in time series # load GeoViews package import", "check the results NO2_week_xr_combined # output the plots # first move to the", "blockage, get maps and time serires plot Second test: get daily maps and", "output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage # week 12", "different days/weeks together # first list all the lats and lons: use (min,max+1/2", "molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot over the small domain [lon_min,lon_max,lat_min,lat_max]", "When downloading the data, look at a larger domain (Suez and its surrounding", "df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial coverage may not", "script is written under version 1.9.1 print(gv.__version__) # there are two backends ('bokeh',", "reduce the file size, you can subset over the small domain # weekly_data", "the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the", "test_lat = test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return", "full grid # Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input", "small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################", "and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on map", "NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you", "return full_grid # create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ #", "tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to", "April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First", "1.9.1 print(gv.__version__) # there are two backends ('bokeh', 'matplotlib') for the GeoViews #", "[data.rename('NO2') for data in weekly_data] # add a time dimension to the data", "oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the full", "os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage # week 12 # day 8-14 #", "week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_')", "read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left',", "numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and", "range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for", "print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use all the data", "lat_max = [] lon_min = [] lon_max = [] for i in range(len(oversampled_data)):", "test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid # create the \"full", "output the plots # first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn", "'''Select TROPOMI files within the start date ('yyyymmdd') and end date ('yyyymmdd')''' #", "the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to", "resolutions, resolution) to keep the max value in Python # just round the", "# select the files and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x:", "in Oversampled_NO2_week] # convert the data to the xarray format for plotting NO2_week", "[] for i in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out", "on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the", "and the end from datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date =", "after the blockage, get maps and time serires plot Second test: get daily", "- start_date sampling_dates = [] for i in range(delta.days + 1): sampling_dates.append((start_date +", "all the sampling dates return sampling_dates # list all the dates Suez_days =", "make a copy first daily_data = NO2_day_xr.copy() # add the variable name daily_data", "a time dimension to the data for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i])", "data:\",len(NO2_day_xr)) # generate corresponding output file names # weekly maps Suez_weeks = list(range(1,17))", "all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the", "# list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray", "= xr.concat(NO2_week_xr,'week') # you can zoom in and change maps, so normally there", "to the data for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week')", "ratio is set to be 2:1 due to the sampling region fig =", "process multiple files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and", "lon] test = np.array(test) test_lat = test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat':", "its surrounding + Mediterranean Sea) import os import glob import numpy as np", "days or during different weeks # read all the data from the weekly", "but it is complicated to save out the results one by one for", "in and change maps, so normally there is no need to make a", "to be excatly the same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon =", "= pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid # create the \"full grid\" domain_grid", "1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read daily", "maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days]", "region fig = plt.figure(figsize=[20,10]) # set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax", "# first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend", "data to generate the geoviews image gv_image = gv_data.to(gv.Image) # decide features of", "= NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for", "'weekly_maps') ################################################################################################ # daily maps # list all the dates def list_dates_between(start_date,end_date): '''Select", "the floats created by Python to be safe # as the \"pd.merge\" step", "in daily_data] # add a time dimension to the data for i in", "selected data print(Oversampled_NO2_file) # Step 2> feed the oversampled data into this data", "dimension to the data for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] =", "add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') #", "quick look at the results # avoid setting \"%matplotlib inline\" as it is", "the xarray data arrays from weekly results # make a copy first weekly_data", "import numpy as np import pandas as pd from netCDF4 import Dataset import", "combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined #", "Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week] # convert the", "bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the", "full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above and the", "data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file)", "close the figure to avoid taking CPU memory plt.close() ################################################################################################ # build a", "can subset over the small domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for", "geoviews.feature as gf import cartopy.crs as crs # it is important to check", "domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)])", "NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables from 1D in the dataframe to", "##################################################################################################################### # build a function to read oversampled TROPOMI NO2 as pandas dataframes", "in weekly_data] # check the results NO2_week_xr_combined # output the plots # first", "min and max of the values on map. Provide a outputfile name. '''", "\"bokeh\" backend to enable interactive map gv.extension('bokeh') # extract data from the combined", "and its surrounding + Mediterranean Sea) import os import glob import numpy as", "i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small =", "Note on this Suez Canal blockage Blockage period: 23-29 March 2021 Data download", "name weekly_data = [data.rename('NO2') for data in weekly_data] # add a time dimension", "to quickly generate maps without a legend to save space on a slide", "= gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to quickly generate maps without a", "we will use \"bokeh\" for interactive plots ################################################################################################ # weekly maps # list", "# list all the dates between the start and the end from datetime", "numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and", "NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') #", "the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data #", "################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically", "max(lon_max) # check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the", "[data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day] # convert the data to the", "gf.coastline # save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') #", "generate maps without a legend to save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name):", "NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)])", "the sampling dates return sampling_dates # list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\")", "netCDF4 import Dataset import xarray as xr ''' Note on this Suez Canal", "to the data for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date')", "high resolution shorelines from NOAA # Think about how to do this with", "# there are two backends ('bokeh', 'matplotlib') for the GeoViews # later we", "# See how TROPOMI NO2 responds to the Suez Canal blockage # When", "turn on \"bokeh\" backend to enable interactive map gv.extension('bokeh') # extract data from", "to decide the max dimension lat_min = [] lat_max = [] lon_min =", "first list all the lats and lons: use (min,max+1/2 resolutions, resolution) to keep", "create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can", "expand_grid(lat,lon): '''list all combinations of lats and lons using expand_grid(lat,lon)''' test = [(A,B)", "complicated to save out the results one by one for multiple days or", "https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to avoid misrepresentation of land and water", "add the variable name weekly_data = [data.rename('NO2') for data in weekly_data] # add", "read each single dataset and match it with the full grid # Step", "domain (Suez and its surrounding + Mediterranean Sea) import os import glob import", "Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the", "print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above and the resolution, we can", "you should be able to use high resolution shorelines from NOAA # Think", "plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') #", "it is important to check your geoviews version, some commands may not work", "= np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build", "together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results NO2_day_xr_combined # output the plots", "= [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week] # convert the data to", "in Oversampled_NO2_files] # use all the data ever sampled to decide the max", "the same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat =", "xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr =", "date ('yyyymmdd')''' # list all the dates between the start and the end", "= 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file) # Step", "is complicated to save out the results one by one for multiple days", "to the xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day]", "with the full grid # Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') #", "import xarray as xr ''' Note on this Suez Canal blockage Blockage period:", "high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to", "to save out the results one by one for multiple days or weeks", "gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to quickly generate maps without a legend", "step later will require the values of \"keys\" to be excatly the same", "# make a copy first daily_data = NO2_day_xr.copy() # add the variable name", "weekly maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number in", "the start date ('yyyymmdd') and end date ('yyyymmdd')''' # list all the dates", "many figures import matplotlib.pyplot as plt import cartopy.crs as crs import geopandas as", "one by one for multiple days or weeks ################################################################################################ ################################################################################################ # So here", "-20,5,60,50 Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data", "plots # first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\"", "NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting NO2_xarray", "print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file names # weekly maps Suez_weeks =", "making maps to have a quick look at the results # avoid setting", "Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################ #", "os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda", "data for i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine", "grid\") # so that we can combine the data from different days/weeks together", "small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate", "the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) #", "map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert", "date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps", "may not be consistent on different days or during different weeks # read", "create your own shapefile, you should be able to use high resolution shorelines", "= sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match with", "some commands may not work in a wrong version # this script is", "# remove the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the", "= [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min)", "https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max)", "import geoviews.feature as gf import cartopy.crs as crs # it is important to", "the aspect ratio is set to be 2:1 due to the sampling region", "# Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to", "test_lon}) return full_grid # create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################", "= {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax", "end date ('yyyymmdd')''' # list all the dates between the start and the", "from datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta =", "\"pd.merge\" step later will require the values of \"keys\" to be excatly the", "plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon',", "# With the dimension above and the resolution, we can create a consistent", "add a time dimension to the data for i in range(len(NO2_day_xr)): NO2_day_xr[i] =", "# So here we use the list comprehensions to process multiple files #################", "produce many figures import matplotlib.pyplot as plt import cartopy.crs as crs import geopandas", "= NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date')", "be 2:1 due to the sampling region fig = plt.figure(figsize=[20,10]) # set the", "'''read the output file for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df =", "is used # If you can crop and create your own shapefile, you", "= input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile", "column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot over the small", "= NO2_week_xr.copy() # add the variable name weekly_data = [data.rename('NO2') for data in", "domain_lon)]) # but it is complicated to save out the results one by", "setting \"%matplotlib inline\" as it is time consuming when we need to produce", "crs # it is important to check your geoviews version, some commands may", "''' Draw the figure in the same way as above, but remove the", "figure size, the aspect ratio is set to be 2:1 due to the", "(Suez and its surrounding + Mediterranean Sea) import os import glob import numpy", "be excatly the same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None)", "and lons in the domain def expand_grid(lat,lon): '''list all combinations of lats and", "plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon',", "ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) #", "[str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots", "\"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file) # Step 2> feed the oversampled", "geoviews image gv_image = gv_data.to(gv.Image) # decide features of the output figure gv_image_out", "# plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label", "# but it is complicated to save out the results one by one", "plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid", "# check the results NO2_day_xr_combined # output the plots # first move to", "pandas as pd from netCDF4 import Dataset import xarray as xr ''' Note", "test = np.array(test) test_lat = test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat,", "# build a function to create a \"full grid\" by listing the full", "sampling_dates # list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\")", "the dataframe to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count", "domain (\"the full grid\") # so that we can combine the data from", "= NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the", "np.array(test) test_lat = test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon})", "set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot", "convert the data to the xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for", "to generatet the bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the", "im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and", "NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray", "# list all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within the start", "data from different days/weeks together # first list all the lats and lons:", "donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data before, during and after the blockage,", "data in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and", "(min,max+1/2 resolutions, resolution) to keep the max value in Python # just round", "at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data", "start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates =", "the file size, you can subset over the small domain # weekly_data =", "# close the figure to avoid taking CPU memory plt.close() ################################################################################################ # check", "and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to quickly", "xarray data arrays from daily results # make a copy first daily_data =", "##################################################################################################################### ##################################################################################################################### # See how TROPOMI NO2 responds to the Suez Canal blockage", "= date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date sampling_dates = [] for i in", "np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a", "[read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week]", "use (min,max+1/2 resolutions, resolution) to keep the max value in Python # just", "load GeoViews package import geoviews as gv import geoviews.feature as gf import cartopy.crs", "the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") #", "data with the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'],", "plt.figure(figsize=[20,10]) # set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain)", "to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to enable interactive", "for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty']", "plt.close() ################################################################################################ # build a function to generatet the bar for the figures", "# turn on \"bokeh\" backend to enable interactive map gv.extension('bokeh') # extract data", "the data ever sampled to decide the max dimension lat_min = [] lat_max", "ax.set_extent(plot_domain) # plot the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add shapefile", "data into this data cleaning routine # read oversampled NO2 data NO2_data =", "resolution) to keep the max value in Python # just round the floats", "arrays from daily results # make a copy first daily_data = NO2_day_xr.copy() #", "the plot rather than the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink':", "[] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max", "# reshape the variables from 1D in the dataframe to the map dimension", "domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape", "= gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the default coastline from GeoViews is", "time consuming when we need to produce many figures import matplotlib.pyplot as plt", "can combine the data from different days/weeks together # first list all the", "os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read daily data or weekly data time", "safe # as the \"pd.merge\" step later will require the values of \"keys\"", "geopandas as gpd # read shape file (Global high resolution shoreline database from", "import os import glob import numpy as np import pandas as pd from", "multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage # week 12 #", "data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day] #", "build a function to generatet the bar for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name):", "the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left',", "colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the", "for data in daily_data] # add a time dimension to the data for", "in the dataframe to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon))", "size, you can subset over the small domain # weekly_data = [data.sel(lat=slice(10,35),lon =", "enable interactive map gv.extension('bokeh') # extract data from the combined xarray gv_data =", "set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on", "a wrong version # this script is written under version 1.9.1 print(gv.__version__) #", "the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read daily data or", "= np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a function to", "# week 12 # day 8-14 # plot weekly data # plot over", "('yyyymmdd') and end date ('yyyymmdd')''' # list all the dates between the start", "the full combinations of lats and lons in the domain def expand_grid(lat,lon): '''list", "# convert to xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray", "pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled TROPOMI NO2''' df", "= xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but", "NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') # check the results", "the xarray data arrays from daily results # make a copy first daily_data", "quickly generate maps without a legend to save space on a slide def", "lat for B in lon] test = np.array(test) test_lat = test[:,0] test_lon =", "= [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for", "# weekly maps # list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") #", "daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_daily =", "[(A,B) for A in lat for B in lon] test = np.array(test) test_lat", "map # but if you have to reduce the file size, you can", "import pandas as pd from netCDF4 import Dataset import xarray as xr '''", "# check the selected data print(Oversampled_NO2_file) # Step 2> feed the oversampled data", "results # avoid setting \"%matplotlib inline\" as it is time consuming when we", "files ################# # weekly data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them", "in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_week] # convert", "print(domain_grid) ################################################################################################ # Now we can read each single dataset and match it", "shorelines from NOAA # Think about how to do this with geopandas #####################################################################################################################", "Oversampled_NO2_week] # convert the data to the xarray format for plotting NO2_week =", "end_date - start_date sampling_dates = [] for i in range(delta.days + 1): sampling_dates.append((start_date", "add a time dimension to the data for i in range(len(NO2_week_xr)): NO2_week_xr[i] =", "set the figure size, the aspect ratio is set to be 2:1 due", "the figure in the same way as above, but remove the plot rather", "for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file names #", "in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric", "size, the aspect ratio is set to be 2:1 due to the sampling", "should be able to use high resolution shorelines from NOAA # Think about", "maps without a legend to save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): '''", "in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35]", "# read all the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"),", "sampling dates return sampling_dates # list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number", "data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week]", "[$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot over the small domain", "match with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day", "in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'],", "use all the data ever sampled to decide the max dimension lat_min =", "Start making maps to have a quick look at the results # avoid", "format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data,", "able to use high resolution shorelines from NOAA # Think about how to", "the data with the full domain grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data =", "# combine the xarray data arrays from daily results # make a copy", "different weeks # read all the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files", "interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps # list", "is no need to make a small map # but if you have", "from netCDF4 import Dataset import xarray as xr ''' Note on this Suez", "lons in the domain def expand_grid(lat,lon): '''list all combinations of lats and lons", "= [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data in Oversampled_NO2_day] # convert the data to", "wrong version # this script is written under version 1.9.1 print(gv.__version__) # there", "# add a time dimension to the data for i in range(len(NO2_week_xr)): NO2_week_xr[i]", "into this data cleaning routine # read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file)", "map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value", "weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data] # check the results", "weeks ################################################################################################ ################################################################################################ # So here we use the list comprehensions to process", "# save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ #", "list all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within the start date", "read oversampled TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file", "we need to produce many figures import matplotlib.pyplot as plt import cartopy.crs as", "data and match with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in", "glob import numpy as np import pandas as pd from netCDF4 import Dataset", "Suez Canal blockage # When downloading the data, look at a larger domain", "data in Oversampled_NO2_week] # convert the data to the xarray format for plotting", "version # this script is written under version 1.9.1 print(gv.__version__) # there are", "# as the \"pd.merge\" step later will require the values of \"keys\" to", "make a copy first weekly_data = NO2_week_xr.copy() # add the variable name weekly_data", "print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max) # With the dimension above and the resolution, we", "date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date - start_date", "datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta = end_date", "save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now,", "all combinations of lats and lons using expand_grid(lat,lon)''' test = [(A,B) for A", "Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews", "projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on", "build a function to read oversampled TROPOMI NO2 as pandas dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file):", "slice(26,60)) for data in weekly_data] # check the results NO2_week_xr_combined # output the", "a function to quickly generate maps without a legend to save space on", "plot daily data # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35]", "= [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at", ": 0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) #", "daily_data] # add a time dimension to the data for i in range(len(NO2_day_xr)):", "the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################", "= plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) #", "plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file names # weekly", "os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to quickly generate maps", "Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat',", "the values on map. Provide a outputfile name. ''' # set the figure", "oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read daily data or weekly", "the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map", "daily data # plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for", "in the domain def expand_grid(lat,lon): '''list all combinations of lats and lons using", "renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps # list all the dates def list_dates_between(start_date,end_date):", "2> feed the oversampled data into this data cleaning routine # read oversampled", "for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat',", "domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the", "plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on map im = input_xr.plot(ax=ax,cmap='jet',vmin=var_min,vmax=var_max) # add", "NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)])", "NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_week] ################# # daily", "together # first list all the lats and lons: use (min,max+1/2 resolutions, resolution)", "Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change input time to read", "the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data =", "################################################################################################ ################################################################################################ # Use GeoViews to combine the maps together in time series", "# make a copy first weekly_data = NO2_week_xr.copy() # add the variable name", "maps to have a quick look at the results # avoid setting \"%matplotlib", "name. ''' # set the figure size, the aspect ratio is set to", "on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25)", "in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'],", "created by Python to be safe # as the \"pd.merge\" step later will", "by listing the full combinations of lats and lons in the domain def", "# For now, the default coastline from GeoViews is used # If you", "''' Input a xarray data array, define the map domain, provide the min", "data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file names", "this data cleaning routine # read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) #", "not be consistent on different days or during different weeks # read all", "test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid # create", "- 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data donwload:", "crs import geopandas as gpd # read shape file (Global high resolution shoreline", "plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid taking", "quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$", "* gf.coastline # save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps')", "= max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max) # check the full dimension", "data # plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i", "for data in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files", "listing the full combinations of lats and lons in the domain def expand_grid(lat,lon):", "different days or during different weeks # read all the data from the", "# print out all the sampling dates return sampling_dates # list all the", "data in daily_data] # add a time dimension to the data for i", "end from datetime import date, timedelta start_date = date(int(start_date[0:4]),int(start_date[4:6]),int(start_date[6:8])) end_date = date(int(end_date[0:4]),int(end_date[4:6]),int(end_date[6:8])) delta", "files and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") #", "the values of \"keys\" to be excatly the same Res = 0.05 domain_lat", "Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample", "sampled to decide the max dimension lat_min = [] lat_max = [] lon_min", "domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) #", "surrounding + Mediterranean Sea) import os import glob import numpy as np import", "# Start making maps to have a quick look at the results #", "gf.coastline # save out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################", "dataframe to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count =", "can read each single dataset and match it with the full grid #", "print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays from daily results", "lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min)", "the domain def expand_grid(lat,lon): '''list all combinations of lats and lons using expand_grid(lat,lon)'''", "GeoViews to combine the maps together in time series # load GeoViews package", "= min(lon_min) lon_max = max(lon_max) # check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min)", "# change input time to read daily data or weekly data time =", "Oversampled_NO2_files] # use all the data ever sampled to decide the max dimension", "# daily maps # list all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files", "# decide features of the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800,", "np import pandas as pd from netCDF4 import Dataset import xarray as xr", "week 12 # day 8-14 # plot weekly data # plot over the", "the data from different days/weeks together # first list all the lats and", "the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the same way", "on this Suez Canal blockage Blockage period: 23-29 March 2021 Data download period:", "= [data.rename('NO2') for data in daily_data] # add a time dimension to the", "for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data before, during and after", "crop and create your own shapefile, you should be able to use high", "build a function to quickly generate maps without a legend to save space", "period: 23-29 March 2021 Data download period: 5 January - 26 April 2021", "range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to combine the maps together in", "lats and lons: use (min,max+1/2 resolutions, resolution) to keep the max value in", "df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial coverage", "= slice(26,60)) for data in weekly_data] # check the results NO2_week_xr_combined # output", "# add the variable name daily_data = [data.rename('NO2') for data in daily_data] #", "list_dates_between(start_date,end_date): '''Select TROPOMI files within the start date ('yyyymmdd') and end date ('yyyymmdd')'''", "misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a", "for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') #", "= test[:,0] test_lon = test[:,1] full_grid = pd.DataFrame({'lat': test_lat, 'lon': test_lon}) return full_grid", "at the results # avoid setting \"%matplotlib inline\" as it is time consuming", "build a function to create a \"full grid\" by listing the full combinations", "dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty = NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to", "import cartopy.crs as crs import geopandas as gpd # read shape file (Global", "gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image gv_image", "https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plot the value on map im =", "# plot over the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in", "dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data", "for data in weekly_data] # add a time dimension to the data for", "a \"full grid\" by listing the full combinations of lats and lons in", "package import geoviews as gv import geoviews.feature as gf import cartopy.crs as crs", "# add shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('')", "data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"),", "i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$", "weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file)", "1D in the dataframe to the map dimension NO2 = NO2_data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) NO2_uncertainty =", "Canal blockage Blockage period: 23-29 March 2021 Data download period: 5 January -", "shapefile ax.add_geometries(world_shore.geometry, crs=ccrs.PlateCarree(),edgecolor='black',facecolor='none') # remove the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save", "the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2]))", "Input a xarray data array, define the map domain, provide the min and", "daily_data = NO2_day_xr.copy() # add the variable name daily_data = [data.rename('NO2') for data", "spatial coverage may not be consistent on different days or during different weeks", "read oversampled data and match with the \"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for", "save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array,", "and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure", "ax.set_extent(plot_domain) # plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar", "weekly data # plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for", "With the dimension above and the resolution, we can create a consistent domain", "lat_min = [] lat_max = [] lon_min = [] lon_max = [] for", "# create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we", "Second test: get daily maps and combine with GeoViews ''' ##################################################################################################################### # build", "################################################################################################ # build a function to generatet the bar for the figures above", "and time serires plot Second test: get daily maps and combine with GeoViews", "1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree())", "= read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the full domain grids NO2_data =", "[data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data", "gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image gv_image = gv_data.to(gv.Image)", "time to read daily data or weekly data time = 'week_1' Oversampled_NO2_file =", "windows for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data before, during and", "for interactive plots ################################################################################################ # weekly maps # list all the weeks Suez_weeks", "= end_date - start_date sampling_dates = [] for i in range(delta.days + 1):", "Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays from weekly results", "x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match with the \"full grid\"", "end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot", "key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match with the \"full", "= NO2_data['NO2_uncertainty'].values.reshape(len(domain_lat),len(domain_lon)) Count = NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting NO2_xarray =", "Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match", "max of the values on map. Provide a outputfile name. ''' # set", "at a larger domain (Suez and its surrounding + Mediterranean Sea) import os", "avoid taking CPU memory plt.close() ################################################################################################ # build a function to generatet the", "\"full grid\" Oversampled_NO2_day = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon'])", "the small domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_small = [26,60,10,35] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) #", "from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data", "normally there is no need to make a small map # but if", "of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine the xarray data arrays from daily results #", "pd from netCDF4 import Dataset import xarray as xr ''' Note on this", "for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at the end", "default coastline from GeoViews is used # If you can crop and create", "as xr ''' Note on this Suez Canal blockage Blockage period: 23-29 March", "combinations of lats and lons using expand_grid(lat,lon)''' test = [(A,B) for A in", "plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column [$10^{15}$ molec. cm$^{-2}$]',0,2,\"Suez_NO2_color_bar\") # plot daily data # plot over", "for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_week] NO2_week_xr = [xr.DataArray(data, coords=[('lat',", "+ str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\") ################################################################################################ # output multiple plots together", "[data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data", "xarray data array, define the map domain, provide the min and max of", "plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage # week 12 # day", "within the start date ('yyyymmdd') and end date ('yyyymmdd')''' # list all the", "range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined", "plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid", "= [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for", "NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the full domain", "have to reduce the file size, you can subset over the small domain", "\"full reolution\" here to avoid misrepresentation of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore =", "resolution, we can create a consistent domain (\"the full grid\") # so that", "as pd from netCDF4 import Dataset import xarray as xr ''' Note on", "Oversampled_NO2_files = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in", "results NO2_week_xr_combined # output the plots # first move to the output directory", "# avoid setting \"%matplotlib inline\" as it is time consuming when we need", "all the dates between the start and the end from datetime import date,", "'lon': test_lon}) return full_grid # create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid)", "coastline from GeoViews is used # If you can crop and create your", "of the values on map. Provide a outputfile name. ''' # set the", "shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to avoid misrepresentation", "the data, look at a larger domain (Suez and its surrounding + Mediterranean", "weekly_data] # check the results NO2_week_xr_combined # output the plots # first move", "and match it with the full grid # Step 1> select the oversampled", "start_date sampling_dates = [] for i in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d'))", "to be safe # as the \"pd.merge\" step later will require the values", "from different days/weeks together # first list all the lats and lons: use", "not work in a wrong version # this script is written under version", "output file names # weekly maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') +", "print(gv.__version__) # there are two backends ('bokeh', 'matplotlib') for the GeoViews # later", "sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match with the", "we can read each single dataset and match it with the full grid", "a consistent domain (\"the full grid\") # so that we can combine the", "sample weekly data before, during and after the blockage, get maps and time", "weekly results # make a copy first weekly_data = NO2_week_xr.copy() # add the", "See how TROPOMI NO2 responds to the Suez Canal blockage # When downloading", "for data in Oversampled_NO2_week] # convert the data to the xarray format for", "Use GeoViews to combine the maps together in time series # load GeoViews", "Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number in Suez_days] print(*Suez_days,sep=\"\\n\")", "Data download period: 5 January - 26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding", "change maps, so normally there is no need to make a small map", "in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') +", "to the Suez Canal blockage # When downloading the data, look at a", "the xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data in Oversampled_NO2_day] NO2_day_xr", "dataframes def read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled TROPOMI NO2''' df =", "all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within the start date ('yyyymmdd')", "bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) # save out", "1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling dates return sampling_dates", "resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) # use \"full reolution\" here to avoid", "0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None) domain_lon = np.arange(lon_min,lon_max+Res/2,Res,dtype=None) domain_lat = np.round(domain_lat,3) domain_lon = np.round(domain_lon,3)", "grids NO2_data = pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the", "df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### #", "them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data", "during different weeks # read all the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output')", "[read_oversampled_NO2(file) for file in Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day]", "# but if you have to reduce the file size, you can subset", "of lats and lons using expand_grid(lat,lon)''' test = [(A,B) for A in lat", "remove the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure", "If you can crop and create your own shapefile, you should be able", "= \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data print(Oversampled_NO2_file) # Step 2> feed the", "figure to avoid taking CPU memory plt.close() ################################################################################################ # build a function to", "[26,60,10,35] for i in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to combine", "('yyyymmdd')''' # list all the dates between the start and the end from", "oversampled data and match with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file", "domain_lon = np.round(domain_lon,3) # build a function to create a \"full grid\" by", "fig = plt.figure(figsize=[20,10]) # set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax =", "can create a consistent domain (\"the full grid\") # so that we can", "the sampling region fig = plt.figure(figsize=[20,10]) # set the map projection and domain:", "slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array, define the map domain,", "renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps # list all the", "output file for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns", "without a legend to save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input", "for the figures above def plot_color_bar(input_xr,plot_domain,label,var_min,var_max,output_figure_name): ''' Draw the figure in the same", "as it is time consuming when we need to produce many figures import", "subset over the small domain # weekly_data = [data.sel(lat=slice(10,35),lon = slice(26,60)) for data", "key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use", "= [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################ # Start making", "cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection", "together in time series # load GeoViews package import geoviews as gv import", "them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data", "as gpd # read shape file (Global high resolution shoreline database from NOAA:", "the plots # first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on", "combined xarray gv_data = gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews", "array, define the map domain, provide the min and max of the values", "daily maps Suez_days = list(range(1,29)) Suez_days = [str('Suez_NO2_map_day_') + str(date_number) for date_number in", "due to the sampling region fig = plt.figure(figsize=[20,10]) # set the map projection", "in time series # load GeoViews package import geoviews as gv import geoviews.feature", "this script is written under version 1.9.1 print(gv.__version__) # there are two backends", "version 1.9.1 print(gv.__version__) # there are two backends ('bokeh', 'matplotlib') for the GeoViews", "the data to generate the geoviews image gv_image = gv_data.to(gv.Image) # decide features", "out the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the", "NO2_week_xr.copy() # add the variable name weekly_data = [data.rename('NO2') for data in weekly_data]", "a small map # but if you have to reduce the file size,", "################################################################################################ # Now we can read each single dataset and match it with", "using expand_grid(lat,lon)''' test = [(A,B) for A in lat for B in lon]", "the dates between the start and the end from datetime import date, timedelta", "colorbar=True, width=800, height=500) * gf.coastline # save out the interactive map renderer =", "cleaning routine # read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the", "\"%matplotlib inline\" as it is time consuming when we need to produce many", "for i in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all", "# build a function to quickly generate maps without a legend to save", "list all the dates Suez_days = list_dates_between(\"20210316\",\"20210412\") print(\"number of days:\",len(Suez_days)) print(*Suez_days,sep=\"\\n\") # combine", "# convert the data to the xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon))", "= gv.Dataset(NO2_week_xr_combined,['lon','lat','week'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image gv_image =", "first daily_data = NO2_day_xr.copy() # add the variable name daily_data = [data.rename('NO2') for", "we can combine the data from different days/weeks together # first list all", "aspect ratio is set to be 2:1 due to the sampling region fig", "= NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables from 1D in the dataframe", "maps and combine with GeoViews ''' ##################################################################################################################### # build a function to read", "range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_small,0,2,Suez_weeks[i]+str('_small')) # generate the color bar at the end plot_color_bar(NO2_week_xr[0],Suez_domain_small,'NO$_2$ tropospheric column", "to avoid taking CPU memory plt.close() ################################################################################################ # check again the data for", "the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate the", "plt.close() ################################################################################################ # check again the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr))", "a larger domain (Suez and its surrounding + Mediterranean Sea) import os import", "= NO2_day_xr.copy() # add the variable name daily_data = [data.rename('NO2') for data in", "be consistent on different days or during different weeks # read all the", "maps # list all the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within the", "a function to create a \"full grid\" by listing the full combinations of", "work in a wrong version # this script is written under version 1.9.1", "rather than the colorbar. ''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad'", "NO2_day_xr = [xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################ # Start", "xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image", "select the files and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2]))", "maps during the blockage # week 12 # day 8-14 # plot weekly", "''' fig = plt.figure(figsize=[20,10]) cbar_keys = {'shrink': 1, 'pad' : 0.05,'orientation':'horizontal','label':label} # set", "decide the max dimension lat_min = [] lat_max = [] lon_min = []", "renderer.save(gv_image_out, 'daily_maps') # For now, the default coastline from GeoViews is used #", "NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data together NO2_day_xr_combined = xr.concat(NO2_day_xr,'date') #", "import glob import numpy as np import pandas as pd from netCDF4 import", "sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files] #", "to make a small map # but if you have to reduce the", "weekly_data = NO2_week_xr.copy() # add the variable name weekly_data = [data.rename('NO2') for data", "figures import matplotlib.pyplot as plt import cartopy.crs as crs import geopandas as gpd", "xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon', domain_lon)]) Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it", "of the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True, width=800, height=500) * gf.coastline", "data in Oversampled_NO2_day] # convert the data to the xarray format for plotting", "list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data", "the blockage # week 12 # day 8-14 # plot weekly data #", "import geoviews as gv import geoviews.feature as gf import cartopy.crs as crs #", "data for i in range(len(NO2_week_xr)): NO2_week_xr[i] = NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine", "# read shape file (Global high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/) #", "first move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to", "directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to enable interactive map gv.extension('bokeh') #", "Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps", "[-20,60,5,50] for i in range(len(NO2_week_xr)): quick_plot(NO2_week_xr[i],Suez_domain_big,0,2,Suez_weeks[i]+str('_big')) # plot over the small domain [lon_min,lon_max,lat_min,lat_max]", "+ str(week_number) for week_number in Suez_weeks] print(*Suez_weeks,sep=\"\\n\") # daily maps Suez_days = list(range(1,29))", "map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) #", "convert to xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray =", "= gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps # list all the dates", "the lats and lons: use (min,max+1/2 resolutions, resolution) to keep the max value", "the variable name weekly_data = [data.rename('NO2') for data in weekly_data] # add a", "= pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables from", "min(lon_min) lon_max = max(lon_max) # check the full dimension print(\"lat_min:\",lat_min) print(\"lat_max:\",lat_max) print(\"lon_min:\",lon_min) print(\"lon_max:\",lon_max)", "dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within the start date ('yyyymmdd') and end", "the interactive map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps #", "combine the xarray data arrays from daily results # make a copy first", "gv_data.to(gv.Image) # decide features of the output figure gv_image_out = gv_image.opts(cmap='jet', clim=(0,2), colorbar=True,", "+ 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print out all the sampling dates return", "[pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True, True]) for data", "cartopy.crs as crs import geopandas as gpd # read shape file (Global high", "[xr.DataArray(data, coords=[('lat', domain_lat),('lon', domain_lon)]) for data in NO2_day] ################################################################################################ # Start making maps", "dimension above and the resolution, we can create a consistent domain (\"the full", "the map domain, provide the min and max of the values on map.", "map. Provide a outputfile name. ''' # set the figure size, the aspect", "Oversampled_NO2_files_daily] Oversampled_NO2_day = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_day] Oversampled_NO2_day = [data.sort_values(by=['lat','lon'], ascending=[True,", "################################################################################################ # Use GeoViews to combine the maps together in time series #", "# When downloading the data, look at a larger domain (Suez and its", "gpd # read shape file (Global high resolution shoreline database from NOAA: https://www.ngdc.noaa.gov/mgg/shorelines/)", "maps # list all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the", "= [data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data] # check the results NO2_week_xr_combined", "weekly data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check the selected data", "= NO2_data['Count'].values.reshape(len(domain_lat),len(domain_lon)) # convert to xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon',", "days or weeks ################################################################################################ ################################################################################################ # So here we use the list comprehensions", "pd.merge(domain_grid,NO2_data,how='left', on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables from 1D", "copy first daily_data = NO2_day_xr.copy() # add the variable name daily_data = [data.rename('NO2')", "taking CPU memory plt.close() ################################################################################################ # build a function to generatet the bar", "reshape the variables from 1D in the dataframe to the map dimension NO2", "later will require the values of \"keys\" to be excatly the same Res", "geoviews as gv import geoviews.feature as gf import cartopy.crs as crs # it", "from weekly results # make a copy first weekly_data = NO2_week_xr.copy() # add", "x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match with the \"full grid\"", "series # load GeoViews package import geoviews as gv import geoviews.feature as gf", "max dimension lat_min = [] lat_max = [] lon_min = [] lon_max =", "file names # weekly maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number)", "or weeks ################################################################################################ ################################################################################################ # So here we use the list comprehensions to", "of land and water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function", "combinations of lats and lons in the domain def expand_grid(lat,lon): '''list all combinations", "get maps and time serires plot Second test: get daily maps and combine", "use the data to generate the geoviews image gv_image = gv_data.to(gv.Image) # decide", "color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) # save", "read_oversampled_NO2(TROPOMI_oversampled_NO2_output_file): '''read the output file for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df", "sampling_dates = [] for i in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) #", "in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min = min(lat_min) lat_max = max(lat_max) lon_min", "GeoViews ''' ##################################################################################################################### # build a function to read oversampled TROPOMI NO2 as", "generate the geoviews image gv_image = gv_data.to(gv.Image) # decide features of the output", "def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array, define the map domain, provide", "the data to the xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data", "Sea) import os import glob import numpy as np import pandas as pd", "print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file names # weekly maps", "under version 1.9.1 print(gv.__version__) # there are two backends ('bokeh', 'matplotlib') for the", "NO2_day] ################################################################################################ # Start making maps to have a quick look at the", "on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array, define the", "the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays from", "to be 2:1 due to the sampling region fig = plt.figure(figsize=[20,10]) # set", "lon_max = [] for i in range(len(oversampled_data)): lat_min.append(oversampled_data[i].lat.min()) lat_max.append(oversampled_data[i].lat.max()) lon_min.append(oversampled_data[i].lon.min()) lon_max.append(oversampled_data[i].lon.max()) lat_min =", "as crs # it is important to check your geoviews version, some commands", "and after the blockage, get maps and time serires plot Second test: get", "lons using expand_grid(lat,lon)''' test = [(A,B) for A in lat for B in", "to xarray for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty,", "resolution shorelines from NOAA # Think about how to do this with geopandas", "to avoid taking CPU memory plt.close() ################################################################################################ # build a function to generatet", "results # make a copy first daily_data = NO2_day_xr.copy() # add the variable", "select the files and sort them numerically Oversampled_NO2_files_daily = sorted(glob.glob(\"Oversample_output_Suez_NO2_day*\"), key=lambda x: int(x.split(\"_\")[-2]))", "min(lat_min) lat_max = max(lat_max) lon_min = min(lon_min) lon_max = max(lon_max) # check the", "for plotting NO2_xarray = xr.DataArray(NO2, coords=[('lat', domain_lat),('lon', domain_lon)]) NO2_uncertainty_xarray = xr.DataArray(NO2_uncertainty, coords=[('lat', domain_lat),('lon',", "for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week = [pd.merge(domain_grid,data,how='left', on=['lat','lon']) for data in Oversampled_NO2_week] Oversampled_NO2_week", "above, but remove the plot rather than the colorbar. ''' fig = plt.figure(figsize=[20,10])", "how TROPOMI NO2 responds to the Suez Canal blockage # When downloading the", "weekly data before, during and after the blockage, get maps and time serires", "print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays from weekly results # make a", "i in range(len(NO2_day_xr)): NO2_day_xr[i] = NO2_day_xr[i].assign_coords(date=Suez_days[i]) NO2_day_xr[i] = NO2_day_xr[i].expand_dims('date') # combine the data", "interactive plots ################################################################################################ # weekly maps # list all the weeks Suez_weeks =", "test = [(A,B) for A in lat for B in lon] test =", "full_grid # create the \"full grid\" domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now", "daily data or weekly data time = 'week_1' Oversampled_NO2_file = \"Oversample_output_Suez_NO2_\"+str(time)+\"_0.05\" # check", "to produce many figures import matplotlib.pyplot as plt import cartopy.crs as crs import", "from daily results # make a copy first daily_data = NO2_day_xr.copy() # add", "routine # read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data", "data arrays from daily results # make a copy first daily_data = NO2_day_xr.copy()", "data in NO2_day] ################################################################################################ # Start making maps to have a quick look", "need to make a small map # but if you have to reduce", "26 April 2021 Domain (lon_min,lat_min,lon_max,lat_max): -20,5,60,50 Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14]", "together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage # week 12 # day 8-14", "True]) for data in Oversampled_NO2_week] # convert the data to the xarray format", "move to the output directory os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # turn on \"bokeh\" backend to enable", "return df ##################################################################################################################### # the spatial coverage may not be consistent on different", "Count_xarray = xr.DataArray(Count, coords=[('lat', domain_lat),('lon', domain_lon)]) # but it is complicated to save", "# generate corresponding output file names # weekly maps Suez_weeks = list(range(1,17)) Suez_weeks", "single dataset and match it with the full grid # Step 1> select", "variable name weekly_data = [data.rename('NO2') for data in weekly_data] # add a time", "water os.chdir(\"/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/shapefiles/gshhg-shp-2.3.7/GSHHS_shp/f\") world_shore = gpd.read_file(\"GSHHS_f_L1.shp\") ################################################################################################ # build a function to quickly generate", "##################################################################################################################### # See how TROPOMI NO2 responds to the Suez Canal blockage #", "values of \"keys\" to be excatly the same Res = 0.05 domain_lat =", "[data.sel(lat=slice(10,35),lon = slice(26,60)) for data in weekly_data] # check the results NO2_week_xr_combined #", "to have a quick look at the results # avoid setting \"%matplotlib inline\"", "x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files,sep=\"\\n\") oversampled_data = [read_oversampled_NO2(file) for file in Oversampled_NO2_files] # use all", "read oversampled NO2 data NO2_data = read_oversampled_NO2(Oversampled_NO2_file) # combine the data with the", "label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) # save out fig.savefig(output_figure_name,", "# the spatial coverage may not be consistent on different days or during", "################################################################################################ # output multiple plots together os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Figures') # maps during the blockage #", "Corresponding hour windows for data donwload: [6,7,8,9,10,11,12,13,14] First test: sample weekly data before,", "out the results one by one for multiple days or weeks ################################################################################################ ################################################################################################", "change input time to read daily data or weekly data time = 'week_1'", "data print(Oversampled_NO2_file) # Step 2> feed the oversampled data into this data cleaning", "################################################################################################ # So here we use the list comprehensions to process multiple files", "plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value on map im = input_xr.plot(ax=ax,cmap='jet',cbar_kwargs=cbar_keys,vmin=var_min,vmax=var_max) # set color", "arrays from weekly results # make a copy first weekly_data = NO2_week_xr.copy() #", "dimension lat_min = [] lat_max = [] lon_min = [] lon_max = []", "of \"keys\" to be excatly the same Res = 0.05 domain_lat = np.arange(lat_min,lat_max+Res/2,Res,dtype=None)", "all the lats and lons: use (min,max+1/2 resolutions, resolution) to keep the max", "# plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in", "Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda x: int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_weekly,sep=\"\\n\") # read oversampled data and match", "GeoViews is used # If you can crop and create your own shapefile,", "combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews", "lats and lons using expand_grid(lat,lon)''' test = [(A,B) for A in lat for", "= [] for i in range(delta.days + 1): sampling_dates.append((start_date + timedelta(days=i)).strftime('%Y%m%d')) # print", "grid\" by listing the full combinations of lats and lons in the domain", "as gv import geoviews.feature as gf import cartopy.crs as crs # it is", "in range(len(NO2_day_xr)): quick_plot(NO2_day_xr[i],Suez_domain_small,0,2,Suez_days[i]+str('_small')) ################################################################################################ ################################################################################################ # Use GeoViews to combine the maps together", "ascending=[True, True]) # reshape the variables from 1D in the dataframe to the", "the variables from 1D in the dataframe to the map dimension NO2 =", "# weekly maps Suez_weeks = list(range(1,17)) Suez_weeks = [str('Suez_NO2_map_week_') + str(week_number) for week_number", "with the \"full grid\" Oversampled_NO2_week = [read_oversampled_NO2(file) for file in Oversampled_NO2_files_weekly] Oversampled_NO2_week =", "data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate corresponding output file names # weekly maps Suez_weeks", "int(x.split(\"_\")[-2])) print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match with the \"full grid\" Oversampled_NO2_day", "weeks # read all the data from the weekly results os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') Oversampled_NO2_files =", "avoid setting \"%matplotlib inline\" as it is time consuming when we need to", "domain def expand_grid(lat,lon): '''list all combinations of lats and lons using expand_grid(lat,lon)''' test", "all the weeks Suez_weeks = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays", "# set the figure size, the aspect ratio is set to be 2:1", "feed the oversampled data into this data cleaning routine # read oversampled NO2", "the dates def list_dates_between(start_date,end_date): '''Select TROPOMI files within the start date ('yyyymmdd') and", "blockage # week 12 # day 8-14 # plot weekly data # plot", "= ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16'] print(*Suez_weeks,sep=\"\\n\") # combine the xarray data arrays from weekly results #", "= gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to generate the geoviews image gv_image =", "to save space on a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data", "data array, define the map domain, provide the min and max of the", "for file in Oversampled_NO2_files] # use all the data ever sampled to decide", "a copy first daily_data = NO2_day_xr.copy() # add the variable name daily_data =", "domain_lat),('lon', domain_lon)]) for data in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select", "# set the map projection: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(plot_domain) # plotthe value", "and create your own shapefile, you should be able to use high resolution", "combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom in and", "map renderer = gv.renderer('bokeh') renderer.save(gv_image_out, 'daily_maps') # For now, the default coastline from", "the full grid # Step 1> select the oversampled data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # change", "gv.renderer('bokeh') renderer.save(gv_image_out, 'weekly_maps') ################################################################################################ # daily maps # list all the dates def", "def list_dates_between(start_date,end_date): '''Select TROPOMI files within the start date ('yyyymmdd') and end date", "domain_grid = expand_grid(domain_lat,domain_lon) print(domain_grid) ################################################################################################ # Now we can read each single dataset", "convert the data to the xarray format for plotting NO2_day = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for", "################################################################################################ # Start making maps to have a quick look at the results", "from GeoViews is used # If you can crop and create your own", "the output file for oversampled TROPOMI NO2''' df = pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7]", "to reduce the file size, you can subset over the small domain #", "df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the spatial coverage may not be", "# check again the data for plotting print(\"weekly data:\",len(NO2_week_xr)) print(\"daily data:\",len(NO2_day_xr)) # generate", "= plt.figure(figsize=[20,10]) # set the map projection and domain: https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#cartopy-projection ax = plt.axes(projection=ccrs.PlateCarree())", "full combinations of lats and lons in the domain def expand_grid(lat,lon): '''list all", "the colorbar and tile plt.delaxes(fig.axes[1]) ax.set_title('') # save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close", "('bokeh', 'matplotlib') for the GeoViews # later we will use \"bokeh\" for interactive", "data from the combined xarray gv_data = gv.Dataset(NO2_day_xr_combined,['lon','lat','date'],'NO2',crs=crs.PlateCarree()) # use the data to", "domain_lon)]) for data in NO2_week] ################# # daily data os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the", "# combine the xarray data arrays from weekly results # make a copy", "print(*Oversampled_NO2_files_daily,sep=\"\\n\") # read oversampled data and match with the \"full grid\" Oversampled_NO2_day =", "on map. Provide a outputfile name. ''' # set the figure size, the", "the maps together in time series # load GeoViews package import geoviews as", "Suez Canal blockage Blockage period: 23-29 March 2021 Data download period: 5 January", "the data to the xarray format for plotting NO2_week = [data['NO2'].values.reshape(len(domain_lat),len(domain_lon)) for data", "= pd.read_csv(TROPOMI_oversampled_NO2_output_file,sep=\"\\s+\",header=None) df = df.iloc[:,2:7] df.columns = ['lat','lon','NO2','Count','NO2_uncertainty'] return df ##################################################################################################################### # the", "8-14 # plot weekly data # plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big", "= NO2_week_xr[i].assign_coords(week=Suez_weeks[i]) NO2_week_xr[i] = NO2_week_xr[i].expand_dims('week') # combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week')", "on \"bokeh\" backend to enable interactive map gv.extension('bokeh') # extract data from the", "np.round(domain_lat,3) domain_lon = np.round(domain_lon,3) # build a function to create a \"full grid\"", "plot over the big domain [lon_min,lon_max,lat_min,lat_max] Suez_domain_big = [-20,60,5,50] for i in range(len(NO2_week_xr)):", "save out fig.savefig(output_figure_name, dpi=100,bbox_inches='tight') # close the figure to avoid taking CPU memory", "os.chdir('/rds/projects/2018/maraisea-glu-01/Study/Research_Data/TROPOMI/project_2_Suez_Canal/Oversample_output') # select the files and sort them numerically Oversampled_NO2_files_weekly = sorted(glob.glob(\"Oversample_output_Suez_NO2_week*\"), key=lambda", "same way as above, but remove the plot rather than the colorbar. '''", "your geoviews version, some commands may not work in a wrong version #", "the default coastline from GeoViews is used # If you can crop and", "a slide def quick_plot(input_xr,plot_domain,var_min,var_max,output_figure_name): ''' Input a xarray data array, define the map", "can crop and create your own shapefile, you should be able to use", "# combine the data together NO2_week_xr_combined = xr.concat(NO2_week_xr,'week') # you can zoom in", "on=['lat','lon']) NO2_data = NO2_data.sort_values(by=['lat','lon'], ascending=[True, True]) # reshape the variables from 1D in", "set color bar label size plt.rcParams.update({'font.size':25}) ax.xaxis.label.set_size(25) # remove the plot plt.delaxes(fig.axes[0]) #" ]
[]
[ "scene_api.scene_data # create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup", "# Copyright (c) Contributors to the Open 3D Engine Project. # For complete", "def on_update_manifest(args): try: scene = args[0] return update_manifest(scene) except RuntimeError as err: print", "None def on_update_manifest(args): try: scene = args[0] return update_manifest(scene) except RuntimeError as err:", "azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a", "(f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None #", "args[0] return update_manifest(scene) except RuntimeError as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except:", "Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright", "please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier:", "try: scene = args[0] return update_manifest(scene) except RuntimeError as err: print (f'ERROR -", "the Open 3D Engine Project. # For complete copyright and license terms please", "# Convert the manifest to a JSON string and return it return sceneManifest.export()", "# # SPDX-License-Identifier: Apache-2.0 OR MIT # # import traceback, sys, uuid, os,", "motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion group to scene manifest sceneManifest.add_motion_group(motionGroup)", "import scene_export_utils import scene_api.motion_group # # Example for exporting MotionGroup scene rules #", "# # Copyright (c) Contributors to the Open 3D Engine Project. # For", "err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler =", "{err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try to", "MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame =", "2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion group", "scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule", "LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT", "- {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try", "'_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor =", "handler for processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect() sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) except:", "processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect() sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) except: sceneJobHandler =", "as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler", "SPDX-License-Identifier: Apache-2.0 OR MIT # # import traceback, sys, uuid, os, json import", "Project. # For complete copyright and license terms please see the LICENSE at", "to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a JSON string and", "= None # try to create SceneAPI handler for processing try: import azlmbr.scene", "terms please see the LICENSE at the root of this distribution. # #", "1.1 motionGroup.add_rule(motionScaleRule) # add motion group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the", "this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import traceback, sys,", "motionGroup.add_rule(motionScaleRule) # add motion group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest", "for processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect() sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) except: sceneJobHandler", "scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try to create", "update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() #", "and license terms please see the LICENSE at the root of this distribution.", "see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0", "import traceback, sys, uuid, os, json import scene_export_utils import scene_api.motion_group # # Example", "create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup()", "def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest()", "None # try to create SceneAPI handler for processing try: import azlmbr.scene sceneJobHandler", "os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor", "the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # #", "scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try to create SceneAPI handler", "= scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule)", "(c) Contributors to the Open 3D Engine Project. # For complete copyright and", "create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule()", "3D Engine Project. # For complete copyright and license terms please see the", "global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try to create SceneAPI handler for", "exporting MotionGroup scene rules # def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create", "import scene_api.scene_data # create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup", "the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR", "complete copyright and license terms please see the LICENSE at the root of", "try to create SceneAPI handler for processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler()", "return it return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try: scene = args[0]", "sys, uuid, os, json import scene_export_utils import scene_api.motion_group # # Example for exporting", "= scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule)", "try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect() sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) except: sceneJobHandler = None", "except RuntimeError as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler", "# add motion group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to", "# SPDX-License-Identifier: Apache-2.0 OR MIT # # import traceback, sys, uuid, os, json", "= None def on_update_manifest(args): try: scene = args[0] return update_manifest(scene) except RuntimeError as", "motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion group to scene", "Apache-2.0 OR MIT # # import traceback, sys, uuid, os, json import scene_export_utils", "manifest to a JSON string and return it return sceneManifest.export() sceneJobHandler = None", "sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try: scene = args[0] return update_manifest(scene) except", "except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try to create SceneAPI", "create SceneAPI handler for processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect() sceneJobHandler.add_callback('OnUpdateManifest',", "Example for exporting MotionGroup scene rules # def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data", "scene_export_utils import scene_api.motion_group # # Example for exporting MotionGroup scene rules # def", "add motion group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a", "manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a JSON string and return it", "import azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create", "at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT #", "= motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion group to scene manifest", "# # Example for exporting MotionGroup scene rules # def update_manifest(scene): import azlmbr.scene.graph", "to a JSON string and return it return sceneManifest.export() sceneJobHandler = None def", "scene = args[0] return update_manifest(scene) except RuntimeError as err: print (f'ERROR - {err}')", "# # import traceback, sys, uuid, os, json import scene_export_utils import scene_api.motion_group #", "the manifest to a JSON string and return it return sceneManifest.export() sceneJobHandler =", "MotionGroup scene rules # def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create a", "on_update_manifest(args): try: scene = args[0] return update_manifest(scene) except RuntimeError as err: print (f'ERROR", "scene_api.motion_group # # Example for exporting MotionGroup scene rules # def update_manifest(scene): import", "of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import traceback,", "<gh_stars>10-100 # # Copyright (c) Contributors to the Open 3D Engine Project. #", "scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a JSON string and return", "print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None", "to the Open 3D Engine Project. # For complete copyright and license terms", "scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) #", "For complete copyright and license terms please see the LICENSE at the root", "SceneAPI handler for processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect() sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest)", "# Example for exporting MotionGroup scene rules # def update_manifest(scene): import azlmbr.scene.graph import", "motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2", "a JSON string and return it return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args):", "scene rules # def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest", "Open 3D Engine Project. # For complete copyright and license terms please see", "rules # def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest sceneManifest", "a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name", "# For complete copyright and license terms please see the LICENSE at the", "distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import traceback, sys, uuid,", "MIT # # import traceback, sys, uuid, os, json import scene_export_utils import scene_api.motion_group", "# create a SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup =", "group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a JSON string", "sceneJobHandler.disconnect() sceneJobHandler = None # try to create SceneAPI handler for processing try:", "SceneManifest sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name =", "motion group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a JSON", "motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion group to scene manifest sceneManifest.add_motion_group(motionGroup) #", "= args[0] return update_manifest(scene) except RuntimeError as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback()", "import scene_api.motion_group # # Example for exporting MotionGroup scene rules # def update_manifest(scene):", "# try to create SceneAPI handler for processing try: import azlmbr.scene sceneJobHandler =", "update_manifest(scene) except RuntimeError as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global", "Engine Project. # For complete copyright and license terms please see the LICENSE", "to create SceneAPI handler for processing try: import azlmbr.scene sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler() sceneJobHandler.connect()", "json import scene_export_utils import scene_api.motion_group # # Example for exporting MotionGroup scene rules", "return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try: scene = args[0] return update_manifest(scene)", "sceneManifest = scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.',", "Convert the manifest to a JSON string and return it return sceneManifest.export() sceneJobHandler", "motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1", "# import traceback, sys, uuid, os, json import scene_export_utils import scene_api.motion_group # #", "# create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule =", "sceneJobHandler = None def on_update_manifest(args): try: scene = args[0] return update_manifest(scene) except RuntimeError", "os, json import scene_export_utils import scene_api.motion_group # # Example for exporting MotionGroup scene", "return update_manifest(scene) except RuntimeError as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback()", "RuntimeError as err: print (f'ERROR - {err}') scene_export_utils.log_exception_traceback() except: scene_export_utils.log_exception_traceback() global sceneJobHandler sceneJobHandler.disconnect()", "sceneJobHandler = None # try to create SceneAPI handler for processing try: import", "= scene_api.scene_data.SceneManifest() # create a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_'))", "traceback, sys, uuid, os, json import scene_export_utils import scene_api.motion_group # # Example for", "and return it return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try: scene =", "= 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion", "OR MIT # # import traceback, sys, uuid, os, json import scene_export_utils import", "a MotionGroup motionGroup = scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame", "sceneManifest.add_motion_group(motionGroup) # Convert the manifest to a JSON string and return it return", "for exporting MotionGroup scene rules # def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data #", "motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add", "JSON string and return it return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try:", "root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import", "= 1.1 motionGroup.add_rule(motionScaleRule) # add motion group to scene manifest sceneManifest.add_motion_group(motionGroup) # Convert", "= os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule())", "it return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try: scene = args[0] return", "uuid, os, json import scene_export_utils import scene_api.motion_group # # Example for exporting MotionGroup", "motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule =", "string and return it return sceneManifest.export() sceneJobHandler = None def on_update_manifest(args): try: scene", "motionGroup.add_rule(motionAdditiveRule) motionScaleRule = motionGroup.create_rule(scene_api.motion_group.MotionScaleRule()) motionScaleRule.scaleFactor = 1.1 motionGroup.add_rule(motionScaleRule) # add motion group to", "Contributors to the Open 3D Engine Project. # For complete copyright and license", "scene_api.motion_group.MotionGroup() motionGroup.name = os.path.basename(scene.sourceFilename.replace('.', '_')) motionAdditiveRule = scene_api.motion_group.MotionAdditiveRule() motionAdditiveRule.sampleFrame = 2 motionGroup.add_rule(motionAdditiveRule) motionScaleRule", "copyright and license terms please see the LICENSE at the root of this", "license terms please see the LICENSE at the root of this distribution. #", "sceneJobHandler sceneJobHandler.disconnect() sceneJobHandler = None # try to create SceneAPI handler for processing", "# def update_manifest(scene): import azlmbr.scene.graph import scene_api.scene_data # create a SceneManifest sceneManifest =" ]
[ "# Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\"", "{'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op)", "test(): model.eval() y = [] t = [] for x_test, y_test in testset:", "for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds += 1/args.n_samples * preds", "[] D_KL = 0 for _ in range(S): y_s, D_KL = model.forward(x) log_p_y_s", "tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to a tf_model and", "* E * torch.sqrt(var_c).view(m, 1, c) # KL divergence to prior MVN(0, I,", "logvar_c = self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m, r, 1) * M", "import foolbox import input_data import argparse from tqdm import tqdm import data_loader import", "evaluation on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config)", "in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = []", "output_layer='logits') adv_accs = [] adv_ents = [] def test_tf(use_adv=True): preds = [] y_test", "x = x.permute(0, 3, 1, 2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x})", "feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred = F.softmax(pred,", "= model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if total", "adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation of our model against fgsm #", "= (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() # Save", "x, y in trainset: x = x.cuda() y = y.cuda() if not args.use_dropout:", "= x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0]", "default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int,", "if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def test(): model.eval()", "D_KL1+D_KL2) if self.training else y else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h =", "cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch", "-1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x", "+= x.shape[0] if total >= 1000: break preds = np.concatenate(preds, 0) y_test =", "h = F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return y def validate(m=args.batch_size): model.eval()", "{:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1): # Create an FGSM attack fgsm_op", "var_c = torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda') # Reparametrization trick W", "parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd',", "not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else:", "= args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda()", "= x.shape[0] r, c = self.in_dim, self.out_dim h = self.fc_xh(x) h = F.relu(h)", "preds, y_test = test_tf() adv_preds += 1/args.n_samples * preds # Compute acc and", "'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training", "attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max': 1.}", "x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\" S = args.train_samples m = args.batch_size", "import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as", "h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy", "test_tf(False) adv_preds += 1/args.n_samples * preds # Compute acc and entropy acc =", "self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m, r, 1) * M # Broadcasted:", "as optim import torch.distributions as dists import numpy as np import scipy.io import", "torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) )", "name = 'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) #", "total = 0 for x, y in testset: x = x.permute(0, 3, 1,", "if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred", "= {'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op =", "0.0001) def forward(self, x, output_weight_params=False): m = x.shape[0] r, c = self.in_dim, self.out_dim", "X.squeeze() if not self.use_dropout: h, D_KL1 = self.fc_xh(X) h = F.relu(h) y, D_KL2", "default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if", "model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def test():", "= self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else y else: h = F.relu(self.fc_xh(X))", "tf_model and wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn,", "default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name =", "D_KL = 0 for _ in range(S): y_s, D_KL = model.forward(x) log_p_y_s =", "import data_loader import math import os import tensorflow as tf from cleverhans.attacks import", "10) def forward(self, X): X = X.squeeze() if not self.use_dropout: h, D_KL1 =", "+= 1/args.n_samples * preds # Compute acc and entropy acc = (np.argmax(adv_preds, axis=1)", "model against fgsm # Use M data adv_preds = 0 for _ in", "self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001,", "for evaluation on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth = True sess =", "adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op =", "1).numpy() else: pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total +=", "parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed)", "+= x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\" S = args.train_samples m =", "= [] y_test = [] total = 0 for x, y in testset:", "import torch import torchvision import torch.nn as nn import torch.nn.functional as F import", "in np.arange(0.1, 1.01, 0.1): # Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess)", "if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for", "in testset: x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y =", "print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1): #", "FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op,", "======================= \"\"\" model.eval() input_shape = (None, 3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10')", "tf from cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport", "= 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset, testset =", "nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim)", "super(Model, self).__init__() self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet)", "def forward(self, X): X = X.squeeze() if not self.use_dropout: h, D_KL1 = self.fc_xh(X)", "= self.fc_xh(X) h = F.relu(h) y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if", "= 0 for _ in range(S): y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y)", "for x_test, y_test in testset: x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy())", "tqdm(range(args.n_samples)): y_s, t = test() y_val += 1/args.n_samples*y_s # Print accuracy acc =", "logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m, r,", "# KL divergence to prior MVN(0, I, I) D_KL = torch.mean( 1/2 *", "h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else:", "= [] for x_test, y_test in testset: x_test = x_test.cuda() y_i = model.forward(x_test)", "\"\"\" ======================= Adversarial examples experiments ======================= \"\"\" model.eval() input_shape = (None, 3, 32,", "True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to", "model.train() return val_acc/total \"\"\" Training \"\"\" S = args.train_samples m = args.batch_size lr", "x.cuda() y = y.cuda() if not args.use_dropout: log_p_y = [] D_KL = 0", "torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def test(): model.eval() y = []", "1, c) # KL divergence to prior MVN(0, I, I) D_KL = torch.mean(", "= np.concatenate(y, 0) t = np.concatenate(t) return y, t y_val = 0 for", "= model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc =", "input_shape = (None, 3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda()", "convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents = [] def", "y_test adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds", "y_test = test_tf(False) adv_preds += 1/args.n_samples * preds # Compute acc and entropy", "c, device='cuda') # Reparametrization trick W = M + torch.sqrt(var_r).view(m, r, 1) *", "parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples',", "h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024,", "against fgsm # Use M data adv_preds = 0 for _ in tqdm(range(args.n_samples)):", "= args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in", "np.concatenate(t) return y, t y_val = 0 for _ in tqdm(range(args.n_samples)): y_s, t", "-0.0001, 0.0001) def forward(self, x, output_weight_params=False): m = x.shape[0] r, c = self.in_dim,", "fgsm # Use M data adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds,", "else: return h, D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__()", "CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents = [] def test_tf(use_adv=True): preds = []", "from tqdm import tqdm import data_loader import math import os import tensorflow as", "= nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001)", "2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else:", "self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self,", "10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self,", "X = X.squeeze() if not self.use_dropout: h, D_KL1 = self.fc_xh(X) h = F.relu(h)", "import CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser()", "parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args", "-torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL else: out = model.forward(x) loss =", "y_test = test_tf() adv_preds += 1/args.n_samples * preds # Compute acc and entropy", "{loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\"", "parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet',", "- c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m, 1, device='cuda')],", "= torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return", "c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda')", "y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc:", "entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv", "0 for x, y in testset: x = x.permute(0, 3, 1, 2) if", "cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true')", "nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') #", "t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments ======================= \"\"\"", "for _ in tqdm(range(args.n_samples)): y_s, t = test() y_val += 1/args.n_samples*y_s # Print", "val_acc = 0 total = 0 for x, y in testset: x =", "h = F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5, training=True) y = self.fc_hy(h)", "a tf_model and wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model =", "# Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps,", "if total >= 1000: break preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0)", "our model against fgsm # Use M data adv_preds = 0 for _", "args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt", "import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import", "self.training else y else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5,", "+ torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1))", "np.arange(0.1, 1.01, 0.1): # Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params", "np.nan_to_num(preds), y_test adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False)", "torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() # We use", "= self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M M =", "= in_dim + 1 self.out_dim = out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim,", "acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy:", "action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0)", "pbar = tqdm(range(args.n_iter)) for i in pbar: for x, y in trainset: x", "= [] def test_tf(use_adv=True): preds = [] y_test = [] total = 0", "self.in_dim, self.out_dim h = self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r =", "eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) #", "+ torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m, 1, c) # KL divergence", "forward(self, x, output_weight_params=False): m = x.shape[0] r, c = self.in_dim, self.out_dim h =", "= parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar',", "ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim)", "np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds,", "= nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim,", "device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL, (M, var_r,", "parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden',", "= 'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load", "(M, var_r, var_c) else: return h, D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50,", "CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments ======================= \"\"\" model.eval() input_shape = (None,", "out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False): m = x.shape[0] r, c", "= nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X): X = X.squeeze()", "torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda') # Reparametrization trick W = M", "type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args =", "* torch.sqrt(var_c).view(m, 1, c) # KL divergence to prior MVN(0, I, I) D_KL", "import torch.distributions as dists import numpy as np import scipy.io import foolbox import", "+= np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\"", "sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params)", "Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def", "in pbar: for x, y in trainset: x = x.cuda() y = y.cuda()", "F import torch.optim as optim import torch.distributions as dists import numpy as np", "y_s, t = test() y_val += 1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1)", "test_tf(use_adv=True): preds = [] y_test = [] total = 0 for x, y", "= CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents = [] def test_tf(use_adv=True): preds =", "def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if not self.use_dropout:", "y_test in testset: x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y", "0) return np.nan_to_num(preds), y_test adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test", "in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds += 1/args.n_samples * preds # Compute", "'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run", "AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False,", "self).__init__() self.in_dim = in_dim + 1 self.out_dim = out_dim self.h_dim = h_dim self.M", "y in trainset: x = x.cuda() y = y.cuda() if not args.use_dropout: log_p_y", "def test_tf(use_adv=True): preds = [] y_test = [] total = 0 for x,", "self.in_dim = in_dim + 1 self.out_dim = out_dim self.h_dim = h_dim self.M =", "accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1): # Create", "config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch", "pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() # We use tf for evaluation on", "nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False): m = x.shape[0] r, c =", "parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True)", "acc: {val_acc:.3f}]') # Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate", "x, output_weight_params=False): m = x.shape[0] r, c = self.in_dim, self.out_dim h = self.fc_xh(x)", "an evaluation of our model against fgsm # Use M data adv_preds =", "self.fc_xh(X) h = F.relu(h) y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training", "self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu =", "torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.distributions", "out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents = [] def test_tf(use_adv=True):", "[] def test_tf(use_adv=True): preds = [] y_test = [] total = 0 for", "testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model,", "data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet,", "model.eval() y = [] t = [] for x_test, y_test in testset: x_test", "0 for _ in tqdm(range(args.n_samples)): y_s, t = test() y_val += 1/args.n_samples*y_s #", "== y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent))", "sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred =", "args.lam*D_KL else: out = model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step()", "y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t = np.concatenate(t)", "test_tf() adv_preds += 1/args.n_samples * preds # Compute acc and entropy acc =", "print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt =", "total += x.shape[0] if total >= 1000: break preds = np.concatenate(preds, 0) y_test", "nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False): m = x.shape[0] r,", "def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1 self.out_dim", "== t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments =======================", "F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M", "1 self.out_dim = out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh =", "y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close()", "__init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1 self.out_dim =", "M # Broadcasted: M is (m, r, c) var_r = torch.exp(logvar_r) var_c =", "model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in", "x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to a tf_model and wrap", "I) D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1),", "nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim,", "(torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r,", "+ 1 self.out_dim = out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh", "to a tf_model and wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model", "y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for", "D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else y else: h =", "evaluation of our model against fgsm # Use M data adv_preds = 0", "* preds # Compute acc and entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean()", "-0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False):", "self.use_dropout: h, D_KL1 = self.fc_xh(X) h = F.relu(h) y, D_KL2 = self.fc_hy(h) return", "= self.M M = mu_scaling.view(m, r, 1) * M # Broadcasted: M is", "y_val += 1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy", "in testset: x = x.permute(0, 3, 1, 2) if use_adv: pred = sess.run(adv_preds_op,", "for x, y in testset: x = x.cuda() y_i = model.forward(x) val_acc +=", "def test(): model.eval() y = [] t = [] for x_test, y_test in", "= np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds = 0", "import argparse from tqdm import tqdm import data_loader import math import os import", "os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class", "total += x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\" S = args.train_samples m", "= test_tf() adv_preds += 1/args.n_samples * preds # Compute acc and entropy acc", "= torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda') # Reparametrization trick W =", "value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar", "for _ in range(S): y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss", "(y, D_KL1+D_KL2) if self.training else y else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h", "return y def validate(m=args.batch_size): model.eval() val_acc = 0 total = 0 for x,", "use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10,", "accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments ======================= \"\"\" model.eval() input_shape", "h, D_KL, (M, var_r, var_c) else: return h, D_KL class Model(nn.Module): def __init__(self,", "x_test, y_test in testset: x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test)", "FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf", "= torch.randn(m, r, c, device='cuda') # Reparametrization trick W = M + torch.sqrt(var_r).view(m,", "default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float,", "for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd)", "pbar: for x, y in trainset: x = x.cuda() y = y.cuda() if", "for x, y in trainset: x = x.cuda() y = y.cuda() if not", "adv_ents = [] def test_tf(use_adv=True): preds = [] y_test = [] total =", "default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50)", "r, 1) * E * torch.sqrt(var_c).view(m, 1, c) # KL divergence to prior", "preds # Compute acc and entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent", "S = args.train_samples m = args.batch_size lr = args.lr lam = args.lam h_dim", "math.log(S)) loss += args.lam*D_KL else: out = model.forward(x) loss = F.cross_entropy(out, y) loss.backward()", "model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}') if", "return (y, D_KL1+D_KL2) if self.training else y else: h = F.relu(self.fc_xh(X)) if self.use_dropout:", "0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight,", "{acc:.3f}') \"\"\" ======================= Adversarial examples experiments ======================= \"\"\" model.eval() input_shape = (None, 3,", "h, D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout =", "in trainset: x = x.cuda() y = y.cuda() if not args.use_dropout: log_p_y =", "\"\"\" model.eval() input_shape = (None, 3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model", "= nn.Sequential(pretrained_model, model) model.eval() # We use tf for evaluation on adversarial data", "y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) -", "tqdm(range(args.n_iter)) for i in pbar: for x, y in trainset: x = x.cuda()", "out = model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc", "torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() # We use tf for evaluation", "nn import torch.nn.functional as F import torch.optim as optim import torch.distributions as dists", "1) - r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h", "model) model.eval() # We use tf for evaluation on adversarial data config =", "pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda())", "from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true')", "X): X = X.squeeze() if not self.use_dropout: h, D_KL1 = self.fc_xh(X) h =", "from cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser", "an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0.,", "opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model if", "np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments", "type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float,", "E * torch.sqrt(var_c).view(m, 1, c) # KL divergence to prior MVN(0, I, I)", "y else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5, training=True) y", "3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1]))", "pytorch model to a tf_model and wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model,", "eps in np.arange(0.1, 1.01, 0.1): # Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model,", "else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X): X", "loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL else: out = model.forward(x)", "var_c) else: return h, D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model,", "0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds += 1/args.n_samples *", "else y else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5, training=True)", "wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs", "= argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int,", "nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out", "lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in pbar: for x, y in", "out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1 self.out_dim = out_dim self.h_dim", "== y.numpy()) total += x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\" S =", "adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01,", "= tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) #", "model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss +=", "args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def test(): model.eval() y =", "D_KL, (M, var_r, var_c) else: return h, D_KL class Model(nn.Module): def __init__(self, h_dim=100,", "self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh =", "self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc = 0 total = 0 for", "experiments ======================= \"\"\" model.eval() input_shape = (None, 3, 32, 32) trainset, testset =", "F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if total >= 1000: break preds", "optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in pbar: for x, y", "from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False,", "M + torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m, 1, c) # KL", "F.relu(h) y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else y else:", "t y_val = 0 for _ in tqdm(range(args.n_samples)): y_s, t = test() y_val", "y in testset: x = x.permute(0, 3, 1, 2) if use_adv: pred =", "x.permute(0, 3, 1, 2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred =", "y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train() return", "\"\"\" def test(): model.eval() y = [] t = [] for x_test, y_test", "[] total = 0 for x, y in testset: x = x.permute(0, 3,", "0) t = np.concatenate(t) return y, t y_val = 0 for _ in", "======================= Adversarial examples experiments ======================= \"\"\" model.eval() input_shape = (None, 3, 32, 32)", "parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam',", "return val_acc/total \"\"\" Training \"\"\" S = args.train_samples m = args.batch_size lr =", "foolbox import input_data import argparse from tqdm import tqdm import data_loader import math", "p=0.5, training=True) y = self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc = 0", "sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to a", "0) - math.log(S)) loss += args.lam*D_KL else: out = model.forward(x) loss = F.cross_entropy(out,", "axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy:", "\"\"\" S = args.train_samples m = args.batch_size lr = args.lr lam = args.lam", "mu_scaling.view(m, r, 1) * M # Broadcasted: M is (m, r, c) var_r", "class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim +", "x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train()", "def forward(self, x, output_weight_params=False): m = x.shape[0] r, c = self.in_dim, self.out_dim h", "= dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL else:", "0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight,", "return y, t y_val = 0 for _ in tqdm(range(args.n_samples)): y_s, t =", "I, I) D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m,", "default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100)", "tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds += 1/args.n_samples * preds # Compute acc", "x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy()", "= mu_scaling.view(m, r, 1) * M # Broadcasted: M is (m, r, c)", "print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments ======================= \"\"\" model.eval()", "torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h,", "**fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation of our model against fgsm", "adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1):", "Adversarial examples experiments ======================= \"\"\" model.eval() input_shape = (None, 3, 32, 32) trainset,", "= np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples", "= tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to a tf_model", "loss += args.lam*D_KL else: out = model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(),", "x.shape[0] if total >= 1000: break preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test,", "from cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport from", "pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')", "W = M + torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m, 1, c)", "action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3)", "y = np.concatenate(y, 0) t = np.concatenate(t) return y, t y_val = 0", "= fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation of our model", "MVN(0, I, I) D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ +", "self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001,", "default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7)", "weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in pbar: for x, y in trainset:", "out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight,", "1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10:", "# We use tf for evaluation on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth", "for x, y in testset: x = x.permute(0, 3, 1, 2) if use_adv:", "cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser =", "for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds += 1/args.n_samples * preds", "adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation of our", "test() y_val += 1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test", "_ in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds += 1/args.n_samples * preds #", "y = [] t = [] for x_test, y_test in testset: x_test =", "self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h)", "cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load',", "fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation of our model against", "D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout", "=============================== Validate ======================================= \"\"\" def test(): model.eval() y = [] t = []", "pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred)", "M = self.M M = mu_scaling.view(m, r, 1) * M # Broadcasted: M", "= tqdm(range(args.n_iter)) for i in pbar: for x, y in trainset: x =", "import scipy.io import foolbox import input_data import argparse from tqdm import tqdm import", "= use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim,", "= args.lr lam = args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model =", "= test() y_val += 1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1) == t)", "opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model", "prior MVN(0, I, I) D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\", "= -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL else: out = model.forward(x) loss", "model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t = np.concatenate(t) return y,", "return h, D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout", "- r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m,", "testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim", "default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100)", "c = self.in_dim, self.out_dim h = self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h)", "self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m,", "- r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h =", "tf for evaluation on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth = True sess", "= self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m, r, 1)", "tqdm import tqdm import data_loader import math import os import tensorflow as tf", "h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X): X = X.squeeze() if not", "args.use_dropout: log_p_y = [] D_KL = 0 for _ in range(S): y_s, D_KL", "print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() # Save data np.save(f'results/cifar/accs_adv_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.npy', adv_accs) np.save(f'results/cifar/ents_adv_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.npy',", "1000: break preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test", "CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout',", "= (np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc))", "h, D_KL1 = self.fc_xh(X) h = F.relu(h) y, D_KL2 = self.fc_hy(h) return (y,", "use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim,", "= [] total = 0 for x, y in testset: x = x.permute(0,", "trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model =", "= F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if total >= 1000: break", "np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\" S", "m = args.batch_size lr = args.lr lam = args.lam h_dim = args.n_hidden h_dim_hypernet", "shape=input_shape) # Convert pytorch model to a tf_model and wrap it in cleverhans", "type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int,", "x = x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total +=", "torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda') # Reparametrization trick", "use tf for evaluation on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth = True", "parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples',", "tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to a tf_model and wrap it in", "[] adv_ents = [] def test_tf(use_adv=True): preds = [] y_test = [] total", "total >= 1000: break preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return", "optim import torch.distributions as dists import numpy as np import scipy.io import foolbox", "log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL else: out =", "as np import scipy.io import foolbox import input_data import argparse from tqdm import", "model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m)", "args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}')", "t.append(y_test) y = np.concatenate(y, 0) t = np.concatenate(t) return y, t y_val =", "parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout:", "0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False): m", "validate(m=args.batch_size): model.eval() val_acc = 0 total = 0 for x, y in testset:", "Use M data adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test =", "model to a tf_model and wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10)", "self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy =", "0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds = 0 for _", "KL divergence to prior MVN(0, I, I) D_KL = torch.mean( 1/2 * (torch.sum(var_r,", "val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train() return val_acc/total \"\"\" Training", "if self.training else y else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h,", "Validate ======================================= \"\"\" def test(): model.eval() y = [] t = [] for", "cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents", "1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation of", "h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1 self.out_dim = out_dim self.h_dim =", "loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss:", "y_test.append(y) total += x.shape[0] if total >= 1000: break preds = np.concatenate(preds, 0)", "entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1): # Create an FGSM attack", "+= 1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy on", "np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds = 0 for", "x = x.cuda() y = y.cuda() if not args.use_dropout: log_p_y = [] D_KL", "adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() # Save data np.save(f'results/cifar/accs_adv_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.npy',", "x, y in testset: x = x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy()", "= 0 for x, y in testset: x = x.cuda() y_i = model.forward(x)", "0.1): # Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps':", "M is (m, r, c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E =", "_ in range(S): y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss =", "1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1)", "in tqdm(range(args.n_samples)): y_s, t = test() y_val += 1/args.n_samples*y_s # Print accuracy acc", "self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m, r, 1) *", "r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m, 1,", "t = [] for x_test, y_test in testset: x_test = x_test.cuda() y_i =", "examples experiments ======================= \"\"\" model.eval() input_shape = (None, 3, 32, 32) trainset, testset", "c) # KL divergence to prior MVN(0, I, I) D_KL = torch.mean( 1/2", "32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model", "h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu", "class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if", "preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds =", "_ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds += 1/args.n_samples * preds #", "1, 2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy()", "parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr',", "type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int,", "preds, y_test = test_tf(False) adv_preds += 1/args.n_samples * preds # Compute acc and", "1/args.n_samples * preds # Compute acc and entropy acc = (np.argmax(adv_preds, axis=1) ==", "if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data", "val acc: {val_acc:.3f}]') # Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" ===============================", "dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL else: out", "r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1),", "else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in pbar:", "parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter',", "(-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1,", "model.eval() input_shape = (None, 3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model =", "val_acc/total \"\"\" Training \"\"\" S = args.train_samples m = args.batch_size lr = args.lr", "data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim", "y in testset: x = x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() ==", "= self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc = 0 total = 0", "pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() #", "Compute acc and entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean()", "x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t =", "import input_data import argparse from tqdm import tqdm import data_loader import math import", "x.shape[0] r, c = self.in_dim, self.out_dim h = self.fc_xh(x) h = F.relu(h) mu_scaling", "= [] t = [] for x_test, y_test in testset: x_test = x_test.cuda()", "numpy as np import scipy.io import foolbox import input_data import argparse from tqdm", "h = self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c", "32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval()", "= np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds = 0 for _ in tqdm(range(args.n_samples)):", "y_val = 0 for _ in tqdm(range(args.n_samples)): y_s, t = test() y_val +=", "config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape)", "0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds += 1/args.n_samples *", "as tf from cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils import", "nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def", "\"\"\" Training \"\"\" S = args.train_samples m = args.batch_size lr = args.lr lam", "self.use_dropout: h = F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return y def validate(m=args.batch_size):", "acc and entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc)", "h = F.relu(h) y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else", ") x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if", "model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter))", "Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim,", "else: pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0]", "trainset: x = x.cuda() y = y.cuda() if not args.use_dropout: log_p_y = []", "# Broadcasted: M is (m, r, c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c)", "(np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg", "torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL, (M, var_r, var_c) else: return h,", "action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100)", "fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op", "= args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel()", "import math import os import tensorflow as tf from cleverhans.attacks import FastGradientMethod from", "preds = [] y_test = [] total = 0 for x, y in", "for eps in np.arange(0.1, 1.01, 0.1): # Create an FGSM attack fgsm_op =", "scipy.io import foolbox import input_data import argparse from tqdm import tqdm import data_loader", "out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight,", "log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss += args.lam*D_KL", "= 0 for _ in tqdm(range(args.n_samples)): y_s, t = test() y_val += 1/args.n_samples*y_s", "parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size',", "h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh =", "args.train_samples m = args.batch_size lr = args.lr lam = args.lam h_dim = args.n_hidden", "output_weight_params: return h, D_KL, (M, var_r, var_c) else: return h, D_KL class Model(nn.Module):", "= model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train() return val_acc/total", "math import os import tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.model", "torch import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim", "r, 1) * M # Broadcasted: M is (m, r, c) var_r =", "if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet)", "h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count:", "type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed)", "Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin'))", "exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module):", "y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t = np.concatenate(t) return y, t", "acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial", "= True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model", "1) * M # Broadcasted: M is (m, r, c) var_r = torch.exp(logvar_r)", "ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() #", "self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001,", "if output_weight_params: return h, D_KL, (M, var_r, var_c) else: return h, D_KL class", "h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy =", "= y.cuda() if not args.use_dropout: log_p_y = [] D_KL = 0 for _", "Convert pytorch model to a tf_model and wrap it in cleverhans tf_model_fn =", "F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc =", "= self.fc_hlogvar_out(h) M = self.M M = mu_scaling.view(m, r, 1) * M #", "= nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001)", "= torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\", "import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False,", "training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100):", "accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() # Save data np.save(f'results/cifar/accs_adv_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.npy', adv_accs) np.save(f'results/cifar/ents_adv_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.npy', adv_ents)", "F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return y", "lr = args.lr lam = args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model", "= tf_model_fn(adv_x_op) # Run an evaluation of our model against fgsm # Use", "use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred =", "# Run an evaluation of our model against fgsm # Use M data", "= model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t = np.concatenate(t) return", "= FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op =", "y.numpy()) total += x.shape[0] model.train() return val_acc/total \"\"\" Training \"\"\" S = args.train_samples", "[] for x_test, y_test in testset: x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i,", "it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs =", "torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m, 1, c) # KL divergence to", "fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op", "accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\" =======================", "y_test = [] total = 0 for x, y in testset: x =", "self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out =", "torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim", "default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name", "trick W = M + torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m, 1,", "y, t y_val = 0 for _ in tqdm(range(args.n_samples)): y_s, t = test()", "preds.append(pred) y_test.append(y) total += x.shape[0] if total >= 1000: break preds = np.concatenate(preds,", "h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in =", "= torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda') # Reparametrization", "import torch.optim as optim import torch.distributions as dists import numpy as np import", "forward(self, X): X = X.squeeze() if not self.use_dropout: h, D_KL1 = self.fc_xh(X) h", "# Print accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10: {acc:.3f}')", "self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim,", "F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total", "super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1 self.out_dim = out_dim self.h_dim = h_dim", "exist_ok=True) # Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self,", "(m, r, c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m, r,", "import os import tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.model import", "adv_accs = [] adv_ents = [] def test_tf(use_adv=True): preds = [] y_test =", "D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S))", "tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents =", "not self.use_dropout: h, D_KL1 = self.fc_xh(X) h = F.relu(h) y, D_KL2 = self.fc_hy(h)", "parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed',", "0 total = 0 for x, y in testset: x = x.cuda() y_i", "log_p_y = [] D_KL = 0 for _ in range(S): y_s, D_KL =", "f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def test(): model.eval() y = [] t", "nn.Linear(h_dim, 10) def forward(self, X): X = X.squeeze() if not self.use_dropout: h, D_KL1", "= x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t", "in range(S): y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y),", "= np.concatenate(t) return y, t y_val = 0 for _ in tqdm(range(args.n_samples)): y_s,", "= data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim =", "3, 1, 2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred),", "r, c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m, r, c,", "y.cuda() if not args.use_dropout: log_p_y = [] D_KL = 0 for _ in", "= self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c =", "5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save", "# Compute acc and entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent =", "ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1", "torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL,", "nn.Sequential(pretrained_model, model) model.eval() # We use tf for evaluation on adversarial data config", "data_loader import math import os import tensorflow as tf from cleverhans.attacks import FastGradientMethod", "1.01, 0.1): # Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params =", "np import scipy.io import foolbox import input_data import argparse from tqdm import tqdm", "type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int,", "pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if", "pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if total >= 1000:", "= args.batch_size lr = args.lr lam = args.lam h_dim = args.n_hidden h_dim_hypernet =", "ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps", "self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh", "* (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c -", "break preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds", "args.batch_size lr = args.lr lam = args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet", "import torch.nn.functional as F import torch.optim as optim import torch.distributions as dists import", "divergence to prior MVN(0, I, I) D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c,", "= optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in pbar: for x,", "of our model against fgsm # Use M data adv_preds = 0 for", "0 for _ in range(S): y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s)", "= F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y)", "testset: x = x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total", "= convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents = []", "testset: x = x.permute(0, 3, 1, 2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op:", "y def validate(m=args.batch_size): model.eval() val_acc = 0 total = 0 for x, y", "as dists import numpy as np import scipy.io import foolbox import input_data import", "adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds +=", "= sess.run(adv_preds_op, feed_dict={x_op: x}) pred = F.softmax(torch.from_numpy(pred), 1).numpy() else: pred = model.forward(x.cuda()) pred", "trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__()", "= ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10)", "nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x,", "return np.nan_to_num(preds), y_test adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test =", "1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if total >= 1000: break preds =", "1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c", "type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn'", "in testset: x = x.cuda() y_i = model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy())", "in_dim, out_dim, h_dim=100): super(ProbHypernet, self).__init__() self.in_dim = in_dim + 1 self.out_dim = out_dim", "= nn.Linear(h_dim, 10) def forward(self, X): X = X.squeeze() if not self.use_dropout: h,", "x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0)", "argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1)", "val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model if not", "count: {np.sum([value.numel() for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(),", "import tqdm import data_loader import math import os import tensorflow as tf from", "0 for x, y in testset: x = x.cuda() y_i = model.forward(x) val_acc", "model.forward(x) val_acc += np.sum(y_i.argmax(dim=1).cpu().numpy() == y.numpy()) total += x.shape[0] model.train() return val_acc/total \"\"\"", "r, c, device='cuda') # Reparametrization trick W = M + torch.sqrt(var_r).view(m, r, 1)", "lam = args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet,", "======================================= \"\"\" def test(): model.eval() y = [] t = [] for x_test,", "np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar',", "model.forward(x.cuda()) pred = F.softmax(pred, 1).cpu().data.numpy() preds.append(pred) y_test.append(y) total += x.shape[0] if total >=", "= x.cuda() y = y.cuda() if not args.use_dropout: log_p_y = [] D_KL =", "output_weight_params=False): m = x.shape[0] r, c = self.in_dim, self.out_dim h = self.fc_xh(x) h", "if self.use_dropout: h = F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return y def", "in_dim + 1 self.out_dim = out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim))", "torch.sqrt(var_c).view(m, 1, c) # KL divergence to prior MVN(0, I, I) D_KL =", "1)) ) x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze()", "tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds += 1/args.n_samples * preds # Compute acc", "{:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1): # Create an", "tqdm import data_loader import math import os import tensorflow as tf from cleverhans.attacks", "= nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False): m = x.shape[0]", "= h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001)", "if not self.use_dropout: h, D_KL1 = self.fc_xh(X) h = F.relu(h) y, D_KL2 =", "as nn import torch.nn.functional as F import torch.optim as optim import torch.distributions as", "{np.sum([value.numel() for value in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr,", "= nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001)", "in model.parameters()])}') if args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar =", "x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params:", "var_r, var_c) else: return h, D_KL class Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False):", "= 0 for x, y in testset: x = x.permute(0, 3, 1, 2)", "as F import torch.optim as optim import torch.distributions as dists import numpy as", "{val_acc:.3f}]') # Save model if not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate =======================================", "= [] D_KL = 0 for _ in range(S): y_s, D_KL = model.forward(x)", "model = nn.Sequential(pretrained_model, model) model.eval() # We use tf for evaluation on adversarial", "'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained')", "training=True) y = self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc = 0 total", "opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i in pbar: for", "= Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value in model.parameters()])}') if args.load:", "y = y.cuda() if not args.use_dropout: log_p_y = [] D_KL = 0 for", "self.fc_hlogvar_out = nn.Linear(h_dim, out_dim) nn.init.uniform_(self.fc_hlogvar_out.weight, -0.0001, 0.0001) def forward(self, x, output_weight_params=False): m =", "= [] adv_ents = [] def test_tf(use_adv=True): preds = [] y_test = []", "in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds += 1/args.n_samples * preds # Compute", "cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits') adv_accs = [] adv_ents = [] def test_tf(use_adv=True): preds", "self.M M = mu_scaling.view(m, r, 1) * M # Broadcasted: M is (m,", "= 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf(False) adv_preds += 1/args.n_samples", "i in pbar: for x, y in trainset: x = x.cuda() y =", "model.eval() # We use tf for evaluation on adversarial data config = tf.ConfigProto()", "nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X): X = X.squeeze() if", "= x.permute(0, 3, 1, 2) if use_adv: pred = sess.run(adv_preds_op, feed_dict={x_op: x}) pred", "type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int,", "1, device='cuda')], 1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL, (M,", "args.load: model.load_state_dict(torch.load(f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin')) else: opt = optim.Adam(model.parameters(), lr, weight_decay=args.wd) pbar = tqdm(range(args.n_iter)) for i", "default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999)", "if not args.use_dropout: log_p_y = [] D_KL = 0 for _ in range(S):", "pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() # We use tf", "(None, 3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model =", "import tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper from", "input_data import argparse from tqdm import tqdm import data_loader import math import os", "range(S): y_s, D_KL = model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0)", "adv_preds += 1/args.n_samples * preds # Compute acc and entropy acc = (np.argmax(adv_preds,", "# Reparametrization trick W = M + torch.sqrt(var_r).view(m, r, 1) * E *", "h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X):", "os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def", "-0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim)", "y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds), y_test adv_preds = 0 for _ in", "ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def", "1) * E * torch.sqrt(var_c).view(m, 1, c) # KL divergence to prior MVN(0,", "tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils", "nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim,", "to prior MVN(0, I, I) D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1)", "Create an FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min':", "= F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f};", "self.out_dim h = self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h)", "Broadcasted: M is (m, r, c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E", "import AccuracyReport from cleverhans.utils_pytorch import convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize',", "not args.use_dropout: log_p_y = [] D_KL = 0 for _ in range(S): y_s,", "not args.load: torch.save(model.state_dict(), f'models/cifar/model_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.bin') \"\"\" =============================== Validate ======================================= \"\"\" def test(): model.eval() y", "Print accuracy acc = np.mean(y_val.argmax(1) == t) print(f'Test accuracy on CIFAR-10: {acc:.3f}') \"\"\"", "= tf.placeholder(tf.float32, shape=input_shape) # Convert pytorch model to a tf_model and wrap it", "args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for", "tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32, shape=input_shape) # Convert", "= (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) for eps in", "else: h = F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5, training=True) y =", "# Use M data adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test", "torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\ -", "= torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() # We use tf for", "data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval()", "= out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim)", "y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else y else: h", "x, y in testset: x = x.permute(0, 3, 1, 2) if use_adv: pred", "import numpy as np import scipy.io import foolbox import input_data import argparse from", "= test_tf(False) adv_preds += 1/args.n_samples * preds # Compute acc and entropy acc", "_ in tqdm(range(args.n_samples)): y_s, t = test() y_val += 1/args.n_samples*y_s # Print accuracy", "= data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model)", "args.lr lam = args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim,", "print('Avg entropy: {:.3f}'.format(ent)) for eps in np.arange(0.1, 1.01, 0.1): # Create an FGSM", "= F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc", "else: out = model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad()", "= 0 total = 0 for x, y in testset: x = x.cuda()", "self.out_dim = out_dim self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim,", "return h, D_KL, (M, var_r, var_c) else: return h, D_KL class Model(nn.Module): def", "self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else y else: h = F.relu(self.fc_xh(X)) if", "import FastGradientMethod from cleverhans.model import CallableModelWrapper from cleverhans.utils import AccuracyReport from cleverhans.utils_pytorch import", "for i in pbar: for x, y in trainset: x = x.cuda() y", "* M # Broadcasted: M is (m, r, c) var_r = torch.exp(logvar_r) var_c", "F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val", "os import tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.model import CallableModelWrapper", "np.concatenate(y, 0) t = np.concatenate(t) return y, t y_val = 0 for _", "torch.optim as optim import torch.distributions as dists import numpy as np import scipy.io", "args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name = 'dropout'", "torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True)", "\"\"\" =============================== Validate ======================================= \"\"\" def test(): model.eval() y = [] t =", "= F.relu(self.fc_xh(X)) if self.use_dropout: h = F.dropout(h, p=0.5, training=True) y = self.fc_hy(h) return", "var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m, r, c, device='cuda') #", "parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name =", "device='cuda') # Reparametrization trick W = M + torch.sqrt(var_r).view(m, r, 1) * E", "model.eval() val_acc = 0 total = 0 for x, y in testset: x", "M = mu_scaling.view(m, r, 1) * M # Broadcasted: M is (m, r,", "r, c = self.in_dim, self.out_dim h = self.fc_xh(x) h = F.relu(h) mu_scaling =", "default=False, action='store_true') parser.add_argument('--train_samples', type=int, default=1) parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3) parser.add_argument('--wd', type=float,", "self.fc_xh = nn.Linear(1024, h_dim) self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X): X =", "testset: x_test = x_test.cuda() y_i = model.forward(x_test) y.append(F.softmax(y_i, dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y,", "convert_pytorch_model_to_tf parser = argparse.ArgumentParser() parser.add_argument('--use_dropout', default=False, action='store_true') parser.add_argument('--normalize', default=False, action='store_true') parser.add_argument('--load', default=False, action='store_true')", "adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() # Save data np.save(f'results/cifar/accs_adv_{name}_{h_dim}_{h_dim_hypernet}_{m}_{lr}_{args.wd}_{args.lam}_{S}.npy', adv_accs)", "Model(nn.Module): def __init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if not", "name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset, testset", "self.fc_hy = nn.Linear(h_dim, 10) def forward(self, X): X = X.squeeze() if not self.use_dropout:", "data adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds", "and wrap it in cleverhans tf_model_fn = convert_pytorch_model_to_tf(model, out_dims=10) cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits')", "and entropy acc = (np.argmax(adv_preds, axis=1) == y_test).mean() ent = (-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent)", "0., 'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an", "D_KL = torch.mean( 1/2 * (torch.sum(var_r, 1)*torch.sum(var_c, 1) \\ + torch.norm(M.view(m, -1), dim=1)**2", "= validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model if not args.load:", "m = x.shape[0] r, c = self.in_dim, self.out_dim h = self.fc_xh(x) h =", "= ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy = ProbHypernet(h_dim, 10, h_dim_hypernet) else: self.fc_xh = nn.Linear(1024,", "dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x =", "= self.in_dim, self.out_dim h = self.fc_xh(x) h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r", "dim=1).cpu().data.numpy()) t.append(y_test) y = np.concatenate(y, 0) t = np.concatenate(t) return y, t y_val", "adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds +=", "FGSM attack fgsm_op = FastGradientMethod(cleverhans_model, sess=sess) fgsm_params = {'eps': eps, 'clip_min': 0., 'clip_max':", "validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]') # Save model if not args.load: torch.save(model.state_dict(),", "torch.randn(m, r, c, device='cuda') # Reparametrization trick W = M + torch.sqrt(var_r).view(m, r,", "default=50) parser.add_argument('--batch_size', type=int, default=200) parser.add_argument('--n_iter', type=int, default=100) parser.add_argument('--randseed', type=int, default=9999) args = parser.parse_args()", "M data adv_preds = 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf()", "t = test() y_val += 1/args.n_samples*y_s # Print accuracy acc = np.mean(y_val.argmax(1) ==", "1) \\ + torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1) -", "= M + torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m, 1, c) #", ">= 1000: break preds = np.concatenate(preds, 0) y_test = np.concatenate(y_test, 0) return np.nan_to_num(preds),", "def validate(m=args.batch_size): model.eval() val_acc = 0 total = 0 for x, y in", "__init__(self, h_dim=100, h_dim_hypernet=50, use_dropout=False): super(Model, self).__init__() self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh", "on CIFAR-10: {acc:.3f}') \"\"\" ======================= Adversarial examples experiments ======================= \"\"\" model.eval() input_shape =", "[] y_test = [] total = 0 for x, y in testset: x", "tf_model_fn(adv_x_op) # Run an evaluation of our model against fgsm # Use M", "h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL, (M, var_r, var_c) else:", "Reparametrization trick W = M + torch.sqrt(var_r).view(m, r, 1) * E * torch.sqrt(var_c).view(m,", "We use tf for evaluation on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth =", "on adversarial data config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op", "h = F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M", "c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x = torch.cat([x, torch.ones(m, 1, device='cuda')], 1)", "D_KL1 = self.fc_xh(X) h = F.relu(h) y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2)", "data config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) x_op = tf.placeholder(tf.float32,", "= F.relu(h) y, D_KL2 = self.fc_hy(h) return (y, D_KL1+D_KL2) if self.training else y", "self).__init__() self.use_dropout = use_dropout if not self.use_dropout: self.fc_xh = ProbHypernet(1024, h_dim, h_dim_hypernet) self.fc_hy", "= 0 for _ in tqdm(range(args.n_samples)): preds, y_test = test_tf() adv_preds += 1/args.n_samples", "args.lam h_dim = args.n_hidden h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter", "nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001, 0.0001) self.fc_hmu = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hmu.weight, -0.0001, 0.0001) self.fc_hlogvar_in", "self.h_dim = h_dim self.M = nn.Parameter(torch.randn(self.in_dim, out_dim)) self.fc_xh = nn.Linear(in_dim, h_dim) nn.init.uniform_(self.fc_xh.weight, -0.0001,", "E = torch.randn(m, r, c, device='cuda') # Reparametrization trick W = M +", "type=int, default=9999) args = parser.parse_args() np.random.seed(args.randseed) torch.manual_seed(args.randseed) name = 'mlcdn' if args.use_dropout: name", "dists import numpy as np import scipy.io import foolbox import input_data import argparse", "total = 0 for x, y in testset: x = x.cuda() y_i =", "[] t = [] for x_test, y_test in testset: x_test = x_test.cuda() y_i", "torch.nn.functional as F import torch.optim as optim import torch.distributions as dists import numpy", "'clip_max': 1.} adv_x_op = fgsm_op.generate(x_op, **fgsm_params) adv_preds_op = tf_model_fn(adv_x_op) # Run an evaluation", "Training \"\"\" S = args.train_samples m = args.batch_size lr = args.lr lam =", "# Convert pytorch model to a tf_model and wrap it in cleverhans tf_model_fn", "= (None, 3, 32, 32) trainset, testset = data_loader.load_dataset('cifar10') pretrained_model = torchvision.models.densenet121(pretrained=True).cuda() pretrained_model", "h_dim_hypernet = args.n_hidden_hypernet model = Model(h_dim, h_dim_hypernet, args.use_dropout).cuda() print(f'Parameter count: {np.sum([value.numel() for value", "default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int, default=50) parser.add_argument('--batch_size', type=int, default=200)", "is (m, r, c) var_r = torch.exp(logvar_r) var_c = torch.exp(logvar_c) E = torch.randn(m,", "= args.train_samples m = args.batch_size lr = args.lr lam = args.lam h_dim =", "-0.0001, 0.0001) self.fc_hlogvar_in = nn.Linear(h_dim, self.in_dim) nn.init.uniform_(self.fc_hlogvar_in.weight, -0.0001, 0.0001) self.fc_hlogvar_out = nn.Linear(h_dim, out_dim)", "loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5) opt.step() opt.zero_grad() val_acc = validate(m) pbar.set_description(f'[Loss: {loss.data.item():.3f}; val acc: {val_acc:.3f}]')", "mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M = self.M M", "= torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL, (M, var_r, var_c) else: return", "(-adv_preds*np.log(adv_preds+1e-8)).sum(1).mean() adv_accs.append(acc) adv_ents.append(ent) print('Adv accuracy: {:.3f}'.format(acc)) print('Avg entropy: {:.3f}'.format(ent)) sess.close() # Save data", "1) h = torch.bmm(x.unsqueeze(1), W).squeeze() if output_weight_params: return h, D_KL, (M, var_r, var_c)", "t = np.concatenate(t) return y, t y_val = 0 for _ in tqdm(range(args.n_samples)):", "torch.distributions as dists import numpy as np import scipy.io import foolbox import input_data", "# Load training data trainset, testset = data_loader.load_dataset('cifar10_pretrained') class ProbHypernet(nn.Module): def __init__(self, in_dim,", "+= args.lam*D_KL else: out = model.forward(x) loss = F.cross_entropy(out, y) loss.backward() nn.utils.clip_grad_value_(model.parameters(), 5)", "y = self.fc_hy(h) return y def validate(m=args.batch_size): model.eval() val_acc = 0 total =", "= X.squeeze() if not self.use_dropout: h, D_KL1 = self.fc_xh(X) h = F.relu(h) y,", "\\ + torch.norm(M.view(m, -1), dim=1)**2 \\ - r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c,", "args.use_dropout: name = 'dropout' os.makedirs('./results/cifar', exist_ok=True) os.makedirs('./models/cifar', exist_ok=True) # Load training data trainset,", "= F.relu(h) mu_scaling = self.fc_hmu(h) logvar_r = self.fc_hlogvar_in(h) logvar_c = self.fc_hlogvar_out(h) M =", "- math.log(S)) loss += args.lam*D_KL else: out = model.forward(x) loss = F.cross_entropy(out, y)", "= model.forward(x) log_p_y_s = dists.Categorical(logits=y_s).log_prob(y) log_p_y.append(log_p_y_s) loss = -torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(S)) loss", "type=float, default=1e-3) parser.add_argument('--wd', type=float, default=0) parser.add_argument('--lam', type=float, default=1e-7) parser.add_argument('--n_hidden', type=int, default=100) parser.add_argument('--n_hidden_hypernet', type=int,", "\\ - r*c - c*torch.sum(logvar_r, 1) - r*torch.sum(logvar_c, 1)) ) x = torch.cat([x,", "Run an evaluation of our model against fgsm # Use M data adv_preds", "argparse from tqdm import tqdm import data_loader import math import os import tensorflow", "W).squeeze() if output_weight_params: return h, D_KL, (M, var_r, var_c) else: return h, D_KL", "= torchvision.models.densenet121(pretrained=True).cuda() pretrained_model = torch.nn.Sequential(*(list(pretrained_model.children())[:-1])) pretrained_model.eval() model = nn.Sequential(pretrained_model, model) model.eval() # We" ]
[ "Generated by Django 3.0.8 on 2020-08-04 03:32 from django.db import migrations, models class", "= [ ('app', '0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo', name='pic', field=models.FileField(blank=True, null=True,", "dependencies = [ ('app', '0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo', name='pic', field=models.FileField(blank=True,", "[ ('app', '0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo', name='pic', field=models.FileField(blank=True, null=True, upload_to='babylon'),", "# Generated by Django 3.0.8 on 2020-08-04 03:32 from django.db import migrations, models", "'0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo', name='pic', field=models.FileField(blank=True, null=True, upload_to='babylon'), ), ]", "2020-08-04 03:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app',", "03:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'),", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ] operations =", "3.0.8 on 2020-08-04 03:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ]", "Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo', name='pic',", "models class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ] operations = [ migrations.AddField(", "('app', '0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo', name='pic', field=models.FileField(blank=True, null=True, upload_to='babylon'), ),", "class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ] operations = [ migrations.AddField( model_name='photo',", "migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ] operations = [", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_photo_hidden'), ] operations", "Django 3.0.8 on 2020-08-04 03:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "on 2020-08-04 03:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "<gh_stars>0 # Generated by Django 3.0.8 on 2020-08-04 03:32 from django.db import migrations,", "by Django 3.0.8 on 2020-08-04 03:32 from django.db import migrations, models class Migration(migrations.Migration):" ]
[ "from MrMap.enums import EnumChoice class DocumentEnum(EnumChoice): \"\"\" Defines all document types \"\"\" CAPABILITY", "class DocumentEnum(EnumChoice): \"\"\" Defines all document types \"\"\" CAPABILITY = \"Capability\" METADATA =", "import EnumChoice class DocumentEnum(EnumChoice): \"\"\" Defines all document types \"\"\" CAPABILITY = \"Capability\"", "EnumChoice class DocumentEnum(EnumChoice): \"\"\" Defines all document types \"\"\" CAPABILITY = \"Capability\" METADATA", "MrMap.enums import EnumChoice class DocumentEnum(EnumChoice): \"\"\" Defines all document types \"\"\" CAPABILITY =", "DocumentEnum(EnumChoice): \"\"\" Defines all document types \"\"\" CAPABILITY = \"Capability\" METADATA = \"Metadata\"" ]
[ "source code is governed by a BSD-style license that can be # found", "of this source code is governed by a BSD-style license that can be", "\"\"\" import operator from qisys import ui import qisys.parsers import qibuild.worktree def configure_parser(parser):", "configs\") for config in configs: ui.info(\"*\", config) default_config = None if worktree: build_worktree", "governed by a BSD-style license that can be # found in the COPYING", "worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is", "qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs: ui.info(\"*\", config) default_config = None", "= qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is using\", default_config,", "qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs: ui.info(\"*\",", "found in the COPYING file. \"\"\"List all the known configs \"\"\" import operator", "this source code is governed by a BSD-style license that can be #", "qisys import ui import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree", "qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg", "qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs =", "COPYING file. \"\"\"List all the known configs \"\"\" import operator from qisys import", "from qisys import ui import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args):", "(c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code", "a BSD-style license that can be # found in the COPYING file. \"\"\"List", "worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known", "= build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is using\", default_config, \"as a default", "if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root,", "# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this", "the COPYING file. \"\"\"List all the known configs \"\"\" import operator from qisys", "qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is using\", default_config, \"as", "config) default_config = None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if", "Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source", "build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is using\", default_config, \"as a default config\")", "= qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs:", "configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs: ui.info(\"*\", config) default_config", "configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs", "the known configs \"\"\" import operator from qisys import ui import qisys.parsers import", "qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for", "Use of this source code is governed by a BSD-style license that can", "import ui import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree =", "None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\",", "SoftBank Robotics. All rights reserved. # Use of this source code is governed", "by a BSD-style license that can be # found in the COPYING file.", "for config in configs: ui.info(\"*\", config) default_config = None if worktree: build_worktree =", "= qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs: ui.info(\"*\", config) default_config =", "qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs: ui.info(\"*\", config)", "code is governed by a BSD-style license that can be # found in", "default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is using\", default_config, \"as a", "ui import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args,", "import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False)", "known configs \"\"\" import operator from qisys import ui import qisys.parsers import qibuild.worktree", "rights reserved. # Use of this source code is governed by a BSD-style", "operator from qisys import ui import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def", "def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read()", "build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree in\", build_worktree.root, \"is using\",", "import operator from qisys import ui import qisys.parsers import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser)", "qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig()", "All rights reserved. # Use of this source code is governed by a", "that can be # found in the COPYING file. \"\"\"List all the known", "2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is", "default_config = None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config:", "= None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config if default_config: ui.info(\"Worktree", "config in configs: ui.info(\"*\", config) default_config = None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree)", "do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\"))", "is governed by a BSD-style license that can be # found in the", "= qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\")", "in configs: ui.info(\"*\", config) default_config = None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config", "file. \"\"\"List all the known configs \"\"\" import operator from qisys import ui", "import qibuild.worktree def configure_parser(parser): qisys.parsers.worktree_parser(parser) def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg =", "configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in configs: ui.info(\"*\", config) default_config = None if", "reserved. # Use of this source code is governed by a BSD-style license", "can be # found in the COPYING file. \"\"\"List all the known configs", "# Use of this source code is governed by a BSD-style license that", "BSD-style license that can be # found in the COPYING file. \"\"\"List all", "<reponame>vbarbaresi/qibuild # Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of", "license that can be # found in the COPYING file. \"\"\"List all the", "def do(args): worktree = qisys.parsers.get_worktree(args, raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values()", "in the COPYING file. \"\"\"List all the known configs \"\"\" import operator from", "qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config in", "all the known configs \"\"\" import operator from qisys import ui import qisys.parsers", "# found in the COPYING file. \"\"\"List all the known configs \"\"\" import", "\"\"\"List all the known configs \"\"\" import operator from qisys import ui import", "be # found in the COPYING file. \"\"\"List all the known configs \"\"\"", "configs \"\"\" import operator from qisys import ui import qisys.parsers import qibuild.worktree def", "ui.info(\"Known configs\") for config in configs: ui.info(\"*\", config) default_config = None if worktree:", "raises=False) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read() configs = qibuild_cfg.configs.values() configs.sort(key=operator.attrgetter(\"name\")) ui.info(\"Known configs\") for config", "Robotics. All rights reserved. # Use of this source code is governed by", "ui.info(\"*\", config) default_config = None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config = build_worktree.default_config", "configs: ui.info(\"*\", config) default_config = None if worktree: build_worktree = qibuild.worktree.BuildWorkTree(worktree) default_config =" ]
[ "system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq) / float(num) out = []", "y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain in the wild", "data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain in the wild type and", "plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000)", "(sys_name) data = np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000]", "plt.title('RMSD of the lasoo domain in the wild type and the I37R mutant", "= data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant", "',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange'", "= 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return", "results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18)", "pyplot as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg", "44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70", "return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i", "lasoo domain in the wild type and the I37R mutant (residues 1 to", "= np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain in", "plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for", "= np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1", "width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum)", "data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo", "avg = len(seq) / float(num) out = [] last = 0.0 while last", "last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg", "800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of", "wild type and the I37R mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16)", "($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list:", "800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i))", "# plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i))", "count=count+1 plt.title('RMSD of the lasoo domain in the wild type and the I37R", "the wild type and the I37R mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time", "out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)])", "data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row", "data = np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:]", "i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for row in", "in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y =", "resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for", "resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print", "if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1])", "#cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list:", "#plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14)", "as np import os import MDAnalysis as mda from matplotlib import pyplot as", "number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y", "plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA", "(beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlim([0,50+0.49]) plt.legend() plt.tight_layout() plt.savefig('res_rmsd.pdf')", "I37R mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16)", "y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row in data if", "# plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x =", "#plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue", "blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks):", "RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1])", "sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for row in data if row[1]", "in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for row in data", "for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$')", "plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq)", "as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq) / float(num) out", "out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in", "= np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1])", "#data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the", "domain in the wild type and the I37R mutant (residues 1 to 44)", "resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs", "data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow", "= data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow')", "0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k", "(ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0", "row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1))", "inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in", "avg)]) last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1)", "data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results", "sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data =", "num): avg = len(seq) / float(num) out = [] last = 0.0 while", "as mda from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat']", "plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row", "print (sys_name) data = np.loadtxt(str(i)) data=[row for row in data if row[1] >=", "row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y", "k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') #", "plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14)", "resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000]", "= np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data)", "row in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y", "Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14)", "in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue", "#plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i)) data =", "import numpy as np import os import MDAnalysis as mda from matplotlib import", "in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y =", "data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1", "row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)])", "data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3]", "len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5))", "and the I37R mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain", "for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001", "(str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3]", "x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on", "for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for row", "last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str)", "(residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14)", "len(seq) / float(num) out = [] last = 0.0 while last < len(seq):", "numpy as np import os import MDAnalysis as mda from matplotlib import pyplot", "plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data", "data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds", "data=[row for row in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x =", "res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row", "resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in", "#yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo", "mda from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue']", "matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq) / float(num)", "domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i", "np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x", "x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row", "row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width =", "color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data =", "system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for row in data if", "separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific", "from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def", "+= avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0", "plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print", ">= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) #", "chunkIt(seq, num): avg = len(seq) / float(num) out = [] last = 0.0", "colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq) / float(num) out = [] last", "[] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last +=", "color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i))", "import MDAnalysis as mda from matplotlib import pyplot as plt import matplotlib.gridspec as", "block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific", "plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper()", "data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row in data if row[1] >=", "the I37R mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD", "0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out", "np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1)", "plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name)", "range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number')", "data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R')", "#num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print", "of the lasoo domain in the wild type and the I37R mutant (residues", "as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg =", "plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001", "in the wild type and the I37R mutant (residues 1 to 44) ',fontsize=18)", "in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) #", "1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5])", "RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlim([0,50+0.49]) plt.legend() plt.tight_layout()", "if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count])", "res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i)) data", "= data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain in the wild type", "np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x", ">= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD", "float(num) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last +", "in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45", "row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for", "bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain", "plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14)", "= data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row in data if row[1]", "data=[row for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int)", "mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond", "# for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec)", "Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlim([0,50+0.49]) plt.legend()", "out.append(seq[int(last):int(last + avg)]) last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1", "data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row in data", "MDAnalysis as mda from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec", "j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6])", "resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar", "mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14)", "/ float(num) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last", "rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1", "<reponame>Miro-Astore/mdanalysis_scripts<filename>graph_2_systems_rmsd.py import numpy as np import os import MDAnalysis as mda from matplotlib", "= len(seq) / float(num) out = [] last = 0.0 while last <", "for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd", "type and the I37R mutant (residues 1 to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo", "800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for", "for row in data if row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001", "plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD", "plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain in the wild type and the", "while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out #cwd=os.getcwd()", "= 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for", "row[1] >= 800000] #data=data[data[:,1]>=800000,:] data=np.array(data) x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1", "gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq) / float(num) out =", "np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k])", "= [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last", "to 44) ',fontsize=18) plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend()", "y = data[:,3] sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow')", "data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j", "plt.xlabel('time (ns)',fontsize=16) plt.ylabel('lasoo domain RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70))", "data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3]", "row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data", "np import os import MDAnalysis as mda from matplotlib import pyplot as plt", "= data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data = np.loadtxt(str(i)) data=[row for row in", "#plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i))", "gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i))", "os import MDAnalysis as mda from matplotlib import pyplot as plt import matplotlib.gridspec", "np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain in the", "np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks)", "sys_count=sys_count+1 row_num=row_num+1 plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT')", "range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum): resrmsd[k]=np.mean(data[:,4+k]) #plt.bar(inds+j*width,resrmsd,width,color=color_vec) res_results[row_num,:]=resrmsd #plt.ylim([0,6]) # plt.ylabel('Residue", "for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width", "specific RMSDs $(\\AA)$') # plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:]", "Lasoo Domain RMSDs (beyond 800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlim([0,50+0.49])", "count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data = np.loadtxt(str(i)) data=[row for", "x = np.array(data[:,1])*0.001 y = data[:,3] plt.plot(x[::2],y[::2],label=sys_name,color=colors[count]) count=count+1 plt.title('RMSD of the lasoo domain", "+ avg)]) last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1", "import pyplot as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num):", "import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq, num): avg = len(seq) /", "import os import MDAnalysis as mda from matplotlib import pyplot as plt import", "if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) blocks=chunkIt(np.array(data[:,0]),numblocks) blocks=np.array(blocks).astype(int) width = 0.45 inds =", "plt.subplot2grid((2,1),(1,0),colspan=1,rowspan=1) separation=0.1 #yellow bar on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue", "print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y =", "on mutant results #plt.bar(np.array([37])-width*0.50,1.05*np.amax(res_results),width,color='yellow') #plt.bar(np.array([37])+width*0.50,1.05*np.amax(res_results),width,color='yellow') plt.bar(inds-width*0.5,res_results[0,:],width,color='orange',label='I37R') plt.bar(inds+width*0.5,res_results[1,:],width,color='tab:blue',label='WT') plt.ylim([0,1.05*np.amax(res_results)]) plt.title('Residue Specific Lasoo Domain RMSDs", "matplotlib import pyplot as plt import matplotlib.gridspec as gridspec system_list=['_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_I37R_3_res_rmsd.dat','_scratch_r16_ma2374_gmx_cftr_2nd_round_310K_wt_1_res_rmsd.dat'] colors=['orange','tab:blue'] def chunkIt(seq,", "< len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list)", "$(\\AA)$') # plt.xlabel('residue number') print (str(i)) data = np.loadtxt(str(i)) rows=(data[:,1]>=800000) data=data[rows,:] resnum=len(data[0,3:-1]) x", "#system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper()", ">= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x = data[:,1]*0.001 y = data[:,3] resnum=len(data[0,3:-1]) data =", "RMSD ($\\AA$)',fontsize=16) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in", "800ns)',fontsize=18) plt.xlabel('residue number',fontsize=14) plt.ylabel('CA RMSD ($\\AA$)',fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlim([0,50+0.49]) plt.legend() plt.tight_layout() plt.savefig('res_rmsd.pdf') plt.show()", "def chunkIt(seq, num): avg = len(seq) / float(num) out = [] last =", "blocks=np.array(blocks).astype(int) width = 0.45 inds = np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1]", "last += avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1)", "the lasoo domain in the wild type and the I37R mutant (residues 1", "= np.array(range(1,len(data[0,3:-1])+1)) # for j in range(numblocks): block=blocks[-1] resrmsd=np.zeros(resnum) for k in range(resnum):", "avg return out #cwd=os.getcwd() #system_list=np.loadtxt('system_list',dtype=str) #num_systems=len(system_list) plt.figure(figsize=(10,5)) numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for", "data = np.loadtxt(str(i)) data=[row for row in data if row[1] >= 800000] data=np.array(data)", "plt.ylim([0,5.5]) plt.legend() color_vec=['blue']*70 color_vec[36]='orange' res_results=np.zeros((2,70)) row_num=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name)", "numblocks=1 sys_count=1 gridspec.GridSpec(2,1) plt.subplot2grid((2,1),(0,0),colspan=1,rowspan=1) count=0 for i in system_list: sys_name=i.split('_')[-4].upper() print (sys_name) data", "data=[row for row in data if row[1] >= 800000] data=np.array(data) resnum=len(data[0,3:-1]) x =" ]
[ "from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into a single", "^^^^^^^^ All parsed plain text files should be merged into a single file", "a file and the first document of another one. \"\"\" def build(self, afm:", "single file to handle them as an unified large corpus data. .. autoclass::", "\"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create()", "print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs,", "to the end of text to avoid # being merged with other line.", ") -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one'))", "<m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as", "one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in", "for line in src: # Add break-line character to the end of text", "to avoid # being merged with other line. line += b'\\n' if not", "file to handle them as an unified large corpus data. .. autoclass:: MergeFiles", "break-line character to the end of text to avoid # being merged with", "files into a single one. Note: All documents are separated by new-line character(``\\\\n``)", "AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in srcs: for line in src: #", "# being merged with other line. line += b'\\n' if not line.endswith(b'\\n') else", "parsed plain text files should be merged into a single file to handle", "are separated by new-line character(``\\\\n``) and this builder automatically appends the new-line character", "AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into a single one. Note: All", "AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into", "merged into a single file to handle them as an unified large corpus", "f'into one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src", "files should be merged into a single file to handle them as an", "and this builder automatically appends the new-line character to avoid mixing the last", "another one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged", "into a single file to handle them as an unified large corpus data.", "All documents are separated by new-line character(``\\\\n``) and this builder automatically appends the", "a single file to handle them as an unified large corpus data. ..", "the new-line character to avoid mixing the last document of a file and", "def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r>", "in srcs: for line in src: # Add break-line character to the end", "character to the end of text to avoid # being merged with other", "avoid # being merged with other line. line += b'\\n' if not line.endswith(b'\\n')", "build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge", "an unified large corpus data. .. autoclass:: MergeFiles \"\"\" from langumo.building import Builder", "\"\"\"Merge files into a single one. Note: All documents are separated by new-line", "afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m>", "Note: All documents are separated by new-line character(``\\\\n``) and this builder automatically appends", "of a file and the first document of another one. \"\"\" def build(self,", "large corpus data. .. autoclass:: MergeFiles \"\"\" from langumo.building import Builder from langumo.utils", "' f'into one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for", "with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in srcs:", "-> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one')) with", "srcs: for src in srcs: for line in src: # Add break-line character", "text files should be merged into a single file to handle them as", "and the first document of another one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs:", "new-line character to avoid mixing the last document of a file and the", "Mergence ^^^^^^^^ All parsed plain text files should be merged into a single", "# Add break-line character to the end of text to avoid # being", "with other line. line += b'\\n' if not line.endswith(b'\\n') else b'' dst.write(line) return", "plain text files should be merged into a single file to handle them", "AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files", "the end of text to avoid # being merged with other line. line", "for src in srcs: for line in src: # Add break-line character to", "as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in srcs: for line", "a single one. Note: All documents are separated by new-line character(``\\\\n``) and this", "file and the first document of another one. \"\"\" def build(self, afm: AuxiliaryFileManager,", "colorful class MergeFiles(Builder): \"\"\"Merge files into a single one. Note: All documents are", "single one. Note: All documents are separated by new-line character(``\\\\n``) and this builder", "new-line character(``\\\\n``) and this builder automatically appends the new-line character to avoid mixing", "first document of another one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile )", "corpus data. .. autoclass:: MergeFiles \"\"\" from langumo.building import Builder from langumo.utils import", "src: # Add break-line character to the end of text to avoid #", "character(``\\\\n``) and this builder automatically appends the new-line character to avoid mixing the", "avoid mixing the last document of a file and the first document of", "from langumo.building import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge", "AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into a single one. Note: All documents", "merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb') as", "the first document of another one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile", "to handle them as an unified large corpus data. .. autoclass:: MergeFiles \"\"\"", "\\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in srcs: for line in src:", ".. autoclass:: MergeFiles \"\"\" from langumo.building import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager,", "the last document of a file and the first document of another one.", "afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb') as dst, \\", "'rb') as srcs: for src in srcs: for line in src: # Add", "langumo.building import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files", "character to avoid mixing the last document of a file and the first", "end of text to avoid # being merged with other line. line +=", "builder automatically appends the new-line character to avoid mixing the last document of", "= afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb') as dst,", "MergeFiles \"\"\" from langumo.building import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class", "to avoid mixing the last document of a file and the first document", "one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile: merged =", "import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into", "being merged with other line. line += b'\\n' if not line.endswith(b'\\n') else b''", "text to avoid # being merged with other line. line += b'\\n' if", "Add break-line character to the end of text to avoid # being merged", "\"\"\" from langumo.building import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder):", "data. .. autoclass:: MergeFiles \"\"\" from langumo.building import Builder from langumo.utils import AuxiliaryFile,", "srcs: for line in src: # Add break-line character to the end of", "AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb')", "class MergeFiles(Builder): \"\"\"Merge files into a single one. Note: All documents are separated", "should be merged into a single file to handle them as an unified", "documents are separated by new-line character(``\\\\n``) and this builder automatically appends the new-line", "in src: # Add break-line character to the end of text to avoid", "import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into a single one. Note:", "files ' f'into one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs:", "automatically appends the new-line character to avoid mixing the last document of a", "handle them as an unified large corpus data. .. autoclass:: MergeFiles \"\"\" from", "line in src: # Add break-line character to the end of text to", "merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in srcs: for", "document of a file and the first document of another one. \"\"\" def", "of another one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) -> AuxiliaryFile:", "All parsed plain text files should be merged into a single file to", "dst, \\ AuxiliaryFile.opens(inputs, 'rb') as srcs: for src in srcs: for line in", "this builder automatically appends the new-line character to avoid mixing the last document", "as srcs: for src in srcs: for line in src: # Add break-line", "*inputs: AuxiliaryFile ) -> AuxiliaryFile: merged = afm.create() print(colorful.render(f'<r>[*]</r> merge <m>{len(inputs)}</m> files '", "autoclass:: MergeFiles \"\"\" from langumo.building import Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful", "them as an unified large corpus data. .. autoclass:: MergeFiles \"\"\" from langumo.building", "langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into a single one.", "of text to avoid # being merged with other line. line += b'\\n'", "merge <m>{len(inputs)}</m> files ' f'into one')) with merged.open('wb') as dst, \\ AuxiliaryFile.opens(inputs, 'rb')", "src in srcs: for line in src: # Add break-line character to the", "one. Note: All documents are separated by new-line character(``\\\\n``) and this builder automatically", "into a single one. Note: All documents are separated by new-line character(``\\\\n``) and", "appends the new-line character to avoid mixing the last document of a file", "document of another one. \"\"\" def build(self, afm: AuxiliaryFileManager, *inputs: AuxiliaryFile ) ->", "unified large corpus data. .. autoclass:: MergeFiles \"\"\" from langumo.building import Builder from", "as an unified large corpus data. .. autoclass:: MergeFiles \"\"\" from langumo.building import", "\"\"\" Mergence ^^^^^^^^ All parsed plain text files should be merged into a", "by new-line character(``\\\\n``) and this builder automatically appends the new-line character to avoid", "merged with other line. line += b'\\n' if not line.endswith(b'\\n') else b'' dst.write(line)", "Builder from langumo.utils import AuxiliaryFile, AuxiliaryFileManager, colorful class MergeFiles(Builder): \"\"\"Merge files into a", "other line. line += b'\\n' if not line.endswith(b'\\n') else b'' dst.write(line) return merged", "separated by new-line character(``\\\\n``) and this builder automatically appends the new-line character to", "last document of a file and the first document of another one. \"\"\"", "MergeFiles(Builder): \"\"\"Merge files into a single one. Note: All documents are separated by", "mixing the last document of a file and the first document of another", "be merged into a single file to handle them as an unified large" ]
[ "dot(B, U) P = dot(A, dot(P, A.T)) + Q return(X,P) def kf_update(X, P,", "dot(H, X) IS = R + dot(H, dot(P, H.T)) K = dot(P, dot(H.T,", "# Applying the Kalman Filter for i in arange(0, N_iter): (X, P) =", "= array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0, 0, 0],", "N_iter = 50 # Applying the Kalman Filter for i in arange(0, N_iter):", "X - tile(M, X.shape()[1]) E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0)", "P, Y, H, R) Y = array([[X[0,0] + abs(0.1 * randn(1)[0])],[X[1, 0] +", "The mean state estimate of the previous step (k−1). P: The state covariance", "numpy import dot, sum, tile, linalg from numpy.linalg import inv def kf_predict(X, P,", "IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1] == 1: DX", "tile(M, X.shape()[1]) E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E =", "exp(-E) elif X.shape()[1] == 1: DX = tile(X, M.shape()[1])- M E = 0.5", "* log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) elif X.shape()[1]", "dot(inv(S), DX)) E = E + 0.5 * M.shape()[0] * log(2 * pi)", "= 0.5 * dot(DX.T, dot(inv(S), DX)) E = E + 0.5 * M.shape()[0]", "IS, LH) = kf_update(X, P, Y, H, R) Y = array([[X[0,0] + abs(0.1", "the Covariance or predictive mean of Y LH: the Predictive probability (likelihood) of", "Covariance or predictive mean of Y LH: the Predictive probability (likelihood) of measurement", "R): \"\"\" K: the Kalman Gain matrix IM: the Mean of predictive distribution", "dot, sum, tile, linalg from numpy.linalg import inv def kf_predict(X, P, A, Q,", "* log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) else: DX", "(P[0],E[0]) from numpy import * from numpy.linalg import inv #time step of mobile", "Q return(X,P) def kf_update(X, P, Y, H, R): \"\"\" K: the Kalman Gain", "dot(H.T, inv(IS))) X = X + dot(K, (Y-IM)) P = P - dot(K,", "matrix. U: The control input. \"\"\" X = dot(A, X) + dot(B, U)", "B, U): \"\"\" X: The mean state estimate of the previous step (k−1).", "exp(-E) return (P[0],E[0]) from numpy import * from numpy.linalg import inv #time step", "matrix IM: the Mean of predictive distribution of Y IS: the Covariance or", "The input effect matrix. U: The control input. \"\"\" X = dot(A, X)", "Python function gauss_pdf. \"\"\" IM = dot(H, X) IS = R + dot(H,", "E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))", "from numpy.linalg import inv #time step of mobile movement dt = 0.1 #", "kf_update(X, P, Y, H, R) Y = array([[X[0,0] + abs(0.1 * randn(1)[0])],[X[1, 0]", "sum, tile, linalg from numpy.linalg import inv def kf_predict(X, P, A, Q, B,", "Filter for i in arange(0, N_iter): (X, P) = kf_predict(X, P, A, Q,", "+ 0.5 * log(det(S)) P = exp(-E) else: DX = X-M E =", "eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0]", "- dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X,", "(likelihood) of measurement which is computed using the Python function gauss_pdf. \"\"\" IM", "(X, P, K, IM, IS, LH) = kf_update(X, P, Y, H, R) Y", "= array([[1, 0, dt , 0], [0, 1, 0, dt], [0, 0, 1,", "estimate of the previous step (k−1). P: The state covariance of previous step", "return (P[0],E[0]) from numpy import * from numpy.linalg import inv #time step of", "X.shape()[1] == 1: DX = tile(X, M.shape()[1])- M E = 0.5 * sum(DX", "+ 0.5 * log(det(S)) P = exp(-E) elif X.shape()[1] == 1: DX =", "0, 0], [0, 1, 0, 0]]) R = eye(Y.shape()[0]) # Number of iterations", "0, 0, 1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) #", "Applying the Kalman Filter for i in arange(0, N_iter): (X, P) = kf_predict(X,", "import inv #time step of mobile movement dt = 0.1 # Initialization of", "Y IS: the Covariance or predictive mean of Y LH: the Predictive probability", "* from numpy.linalg import inv #time step of mobile movement dt = 0.1", "matrix. Q: The process noise covariance matrix. B: The input effect matrix. U:", "mobile movement dt = 0.1 # Initialization of state matrices X = array([[0.0],", "= exp(-E) elif X.shape()[1] == 1: DX = tile(X, M.shape()[1])- M E =", "from numpy.linalg import inv def kf_predict(X, P, A, Q, B, U): \"\"\" X:", "(X, P) = kf_predict(X, P, A, Q, B, U) (X, P, K, IM,", "* sum(DX * (dot(inv(S), DX)), axis=0) E = E + 0.5 * M.shape()[0]", "P = dot(A, dot(P, A.T)) + Q return(X,P) def kf_update(X, P, Y, H,", "= 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E = E + 0.5", "else: DX = X-M E = 0.5 * dot(DX.T, dot(inv(S), DX)) E =", "or predictive mean of Y LH: the Predictive probability (likelihood) of measurement which", "(Y-IM)) P = P - dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS)", "B, U) (X, P, K, IM, IS, LH) = kf_update(X, P, Y, H,", "DX)) E = E + 0.5 * M.shape()[0] * log(2 * pi) +", "numpy.linalg import inv #time step of mobile movement dt = 0.1 # Initialization", "transition n × n matrix. Q: The process noise covariance matrix. B: The", "the Predictive probability (likelihood) of measurement which is computed using the Python function", "Kalman Filter for i in arange(0, N_iter): (X, P) = kf_predict(X, P, A,", "IS: the Covariance or predictive mean of Y LH: the Predictive probability (likelihood)", "DX = tile(X, M.shape()[1])- M E = 0.5 * sum(DX * (dot(inv(S), DX)),", "pi) + 0.5 * log(det(S)) P = exp(-E) elif X.shape()[1] == 1: DX", "matrices X = array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01, 0.01, 0.01, 0.01))", "\"\"\" X = dot(A, X) + dot(B, U) P = dot(A, dot(P, A.T))", "0.5 * log(det(S)) P = exp(-E) else: DX = X-M E = 0.5", "computed using the Python function gauss_pdf. \"\"\" IM = dot(H, X) IS =", "arange(0, N_iter): (X, P) = kf_predict(X, P, A, Q, B, U) (X, P,", "= X-M E = 0.5 * dot(DX.T, dot(inv(S), DX)) E = E +", "1, 0, 0]]) R = eye(Y.shape()[0]) # Number of iterations in Kalman Filter", "0.5 * log(det(S)) P = exp(-E) return (P[0],E[0]) from numpy import * from", "0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]])", "zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H", "X = X + dot(K, (Y-IM)) P = P - dot(K, dot(IS, K.T))", "n matrix. Q: The process noise covariance matrix. B: The input effect matrix.", "kf_predict(X, P, A, Q, B, U) (X, P, K, IM, IS, LH) =", "(dot(inv(S), DX)), axis=0) E = E + 0.5 * M.shape()[0] * log(2 *", "sum(DX * (dot(inv(S), DX)), axis=0) E = E + 0.5 * M.shape()[0] *", "U = zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] +", "+ Q return(X,P) def kf_update(X, P, Y, H, R): \"\"\" K: the Kalman", "0.01, 0.01, 0.01)) A = array([[1, 0, dt , 0], [0, 1, 0,", "dot(H, dot(P, H.T)) K = dot(P, dot(H.T, inv(IS))) X = X + dot(K,", "M, S): if M.shape()[1] == 1: DX = X - tile(M, X.shape()[1]) E", "array([[1, 0, 0, 0], [0, 1, 0, 0]]) R = eye(Y.shape()[0]) # Number", "\"\"\" from numpy import dot, sum, tile, linalg from numpy.linalg import inv def", "M.shape()[0] * log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) elif", "of iterations in Kalman Filter N_iter = 50 # Applying the Kalman Filter", "P = P - dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS) return", "* M.shape()[0] * log(2 * pi) + 0.5 * log(det(S)) P = exp(-E)", "* log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) return (P[0],E[0])", "P = exp(-E) else: DX = X-M E = 0.5 * dot(DX.T, dot(inv(S),", "= kf_predict(X, P, A, Q, B, U) (X, P, K, IM, IS, LH)", "IS = R + dot(H, dot(P, H.T)) K = dot(P, dot(H.T, inv(IS))) X", "0, dt , 0], [0, 1, 0, dt], [0, 0, 1, 0], [0,", "log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) else: DX =", "elif X.shape()[1] == 1: DX = tile(X, M.shape()[1])- M E = 0.5 *", "= eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices Y =", "Kalman Gain matrix IM: the Mean of predictive distribution of Y IS: the", "# Initialization of state matrices X = array([[0.0], [0.0], [0.1], [0.1]]) P =", "Filter N_iter = 50 # Applying the Kalman Filter for i in arange(0,", "0, 0]]) R = eye(Y.shape()[0]) # Number of iterations in Kalman Filter N_iter", "S): if M.shape()[1] == 1: DX = X - tile(M, X.shape()[1]) E =", "[0, 1, 0, 0]]) R = eye(Y.shape()[0]) # Number of iterations in Kalman", "(k−1). P: The state covariance of previous step (k−1). A: The transition n", "E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E = E +", "= dot(A, dot(P, A.T)) + Q return(X,P) def kf_update(X, P, Y, H, R):", "0]]) R = eye(Y.shape()[0]) # Number of iterations in Kalman Filter N_iter =", "LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1]", "\"\"\" X: The mean state estimate of the previous step (k−1). P: The", "state covariance of previous step (k−1). A: The transition n × n matrix.", "n × n matrix. Q: The process noise covariance matrix. B: The input", "= eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])],", "pi) + 0.5 * log(det(S)) P = exp(-E) else: DX = X-M E", "= X + dot(K, (Y-IM)) P = P - dot(K, dot(IS, K.T)) LH", "http://arxiv.org/pdf/1204.0375.pdf \"\"\" from numpy import dot, sum, tile, linalg from numpy.linalg import inv", "from numpy import dot, sum, tile, linalg from numpy.linalg import inv def kf_predict(X,", "U: The control input. \"\"\" X = dot(A, X) + dot(B, U) P", "measurement which is computed using the Python function gauss_pdf. \"\"\" IM = dot(H,", "Y, H, R): \"\"\" K: the Kalman Gain matrix IM: the Mean of", "(k−1). A: The transition n × n matrix. Q: The process noise covariance", "Y, H, R) Y = array([[X[0,0] + abs(0.1 * randn(1)[0])],[X[1, 0] + abs(0.1", "[0, 0, 0, 1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1))", "Q, B, U): \"\"\" X: The mean state estimate of the previous step", "50 # Applying the Kalman Filter for i in arange(0, N_iter): (X, P)", "dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S):", "P, A, Q, B, U): \"\"\" X: The mean state estimate of the", "M.shape()[0] * log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) else:", "axis=0) E = E + 0.5 * M.shape()[0] * log(2 * pi) +", "# Number of iterations in Kalman Filter N_iter = 50 # Applying the", "in Kalman Filter N_iter = 50 # Applying the Kalman Filter for i", "previous step (k−1). A: The transition n × n matrix. Q: The process", "noise covariance matrix. B: The input effect matrix. U: The control input. \"\"\"", "X + dot(K, (Y-IM)) P = P - dot(K, dot(IS, K.T)) LH =", "tile(X, M.shape()[1])- M E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E", "array([[1, 0, dt , 0], [0, 1, 0, dt], [0, 0, 1, 0],", "- tile(M, X.shape()[1]) E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E", "0], [0, 0, 0, 1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U =", "# Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H =", "dt], [0, 0, 1, 0], [0, 0, 0, 1]]) Q = eye(X.shape()[0]) B", "A = array([[1, 0, dt , 0], [0, 1, 0, dt], [0, 0,", "= array([[1, 0, 0, 0], [0, 1, 0, 0]]) R = eye(Y.shape()[0]) #", "[X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0, 0, 0], [0, 1, 0, 0]])", "abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0, 0, 0], [0, 1, 0,", "0, 1, 0], [0, 0, 0, 1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0])", "def kf_update(X, P, Y, H, R): \"\"\" K: the Kalman Gain matrix IM:", "U) P = dot(A, dot(P, A.T)) + Q return(X,P) def kf_update(X, P, Y,", "log(det(S)) P = exp(-E) elif X.shape()[1] == 1: DX = tile(X, M.shape()[1])- M", "X: The mean state estimate of the previous step (k−1). P: The state", "Y LH: the Predictive probability (likelihood) of measurement which is computed using the", "\"\"\" From http://arxiv.org/pdf/1204.0375.pdf \"\"\" from numpy import dot, sum, tile, linalg from numpy.linalg", "dot(K, (Y-IM)) P = P - dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM,", "dot(P, A.T)) + Q return(X,P) def kf_update(X, P, Y, H, R): \"\"\" K:", "IM: the Mean of predictive distribution of Y IS: the Covariance or predictive", "E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5", "0.5 * dot(DX.T, dot(inv(S), DX)) E = E + 0.5 * M.shape()[0] *", "[0, 0, 1, 0], [0, 0, 0, 1]]) Q = eye(X.shape()[0]) B =", "\"\"\" IM = dot(H, X) IS = R + dot(H, dot(P, H.T)) K", "array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0, 0, 0], [0,", "X.shape()[1]) E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E = E", "R + dot(H, dot(P, H.T)) K = dot(P, dot(H.T, inv(IS))) X = X", "of state matrices X = array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01, 0.01,", "X) IS = R + dot(H, dot(P, H.T)) K = dot(P, dot(H.T, inv(IS)))", "IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1] == 1: DX =", "step (k−1). A: The transition n × n matrix. Q: The process noise", "= zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]])", "distribution of Y IS: the Covariance or predictive mean of Y LH: the", "0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E = E + 0.5 *", ", 0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0,", "P = diag((0.01, 0.01, 0.01, 0.01)) A = array([[1, 0, dt , 0],", "1: DX = tile(X, M.shape()[1])- M E = 0.5 * sum(DX * (dot(inv(S),", "exp(-E) else: DX = X-M E = 0.5 * dot(DX.T, dot(inv(S), DX)) E", "= 0.1 # Initialization of state matrices X = array([[0.0], [0.0], [0.1], [0.1]])", "numpy import * from numpy.linalg import inv #time step of mobile movement dt", "0.01, 0.01)) A = array([[1, 0, dt , 0], [0, 1, 0, dt],", "= dot(P, dot(H.T, inv(IS))) X = X + dot(K, (Y-IM)) P = P", "R) Y = array([[X[0,0] + abs(0.1 * randn(1)[0])],[X[1, 0] + abs(0.1 * randn(1)[0])]])", "import * from numpy.linalg import inv #time step of mobile movement dt =", "U) (X, P, K, IM, IS, LH) = kf_update(X, P, Y, H, R)", "K = dot(P, dot(H.T, inv(IS))) X = X + dot(K, (Y-IM)) P =", "IM, IS, LH) = kf_update(X, P, Y, H, R) Y = array([[X[0,0] +", "return(X,P) def kf_update(X, P, Y, H, R): \"\"\" K: the Kalman Gain matrix", "* dot(DX.T, dot(inv(S), DX)) E = E + 0.5 * M.shape()[0] * log(2", "+ dot(K, (Y-IM)) P = P - dot(K, dot(IS, K.T)) LH = gauss_pdf(Y,", "P, K, IM, IS, LH) = kf_update(X, P, Y, H, R) Y =", "+ 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S)) P", "effect matrix. U: The control input. \"\"\" X = dot(A, X) + dot(B,", "B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0] +", "0], [0, 1, 0, 0]]) R = eye(Y.shape()[0]) # Number of iterations in", "dot(P, dot(H.T, inv(IS))) X = X + dot(K, (Y-IM)) P = P -", "i in arange(0, N_iter): (X, P) = kf_predict(X, P, A, Q, B, U)", "which is computed using the Python function gauss_pdf. \"\"\" IM = dot(H, X)", "DX)), axis=0) E = E + 0.5 * M.shape()[0] * log(2 * pi)", "diag((0.01, 0.01, 0.01, 0.01)) A = array([[1, 0, dt , 0], [0, 1,", "0.01)) A = array([[1, 0, dt , 0], [0, 1, 0, dt], [0,", "the Python function gauss_pdf. \"\"\" IM = dot(H, X) IS = R +", "A, Q, B, U): \"\"\" X: The mean state estimate of the previous", "gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1] == 1:", "predictive distribution of Y IS: the Covariance or predictive mean of Y LH:", "dot(P, H.T)) K = dot(P, dot(H.T, inv(IS))) X = X + dot(K, (Y-IM))", "= array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01, 0.01, 0.01, 0.01)) A =", "probability (likelihood) of measurement which is computed using the Python function gauss_pdf. \"\"\"", "= kf_update(X, P, Y, H, R) Y = array([[X[0,0] + abs(0.1 * randn(1)[0])],[X[1,", "input. \"\"\" X = dot(A, X) + dot(B, U) P = dot(A, dot(P,", "IM = dot(H, X) IS = R + dot(H, dot(P, H.T)) K =", "A: The transition n × n matrix. Q: The process noise covariance matrix.", "1: DX = X - tile(M, X.shape()[1]) E = 0.5 * sum(DX *", "The control input. \"\"\" X = dot(A, X) + dot(B, U) P =", "H, R): \"\"\" K: the Kalman Gain matrix IM: the Mean of predictive", "= E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 *", "= diag((0.01, 0.01, 0.01, 0.01)) A = array([[1, 0, dt , 0], [0,", "gauss_pdf. \"\"\" IM = dot(H, X) IS = R + dot(H, dot(P, H.T))", "P: The state covariance of previous step (k−1). A: The transition n ×", "#time step of mobile movement dt = 0.1 # Initialization of state matrices", "M E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E = E", "Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1,", "= eye(Y.shape()[0]) # Number of iterations in Kalman Filter N_iter = 50 #", "Q: The process noise covariance matrix. B: The input effect matrix. U: The", "+ abs(randn(1)[0])]]) H = array([[1, 0, 0, 0], [0, 1, 0, 0]]) R", "Number of iterations in Kalman Filter N_iter = 50 # Applying the Kalman", "step (k−1). P: The state covariance of previous step (k−1). A: The transition", "kf_update(X, P, Y, H, R): \"\"\" K: the Kalman Gain matrix IM: the", "0, 0, 0], [0, 1, 0, 0]]) R = eye(Y.shape()[0]) # Number of", "is computed using the Python function gauss_pdf. \"\"\" IM = dot(H, X) IS", "= exp(-E) return (P[0],E[0]) from numpy import * from numpy.linalg import inv #time", "dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M,", "P, A, Q, B, U) (X, P, K, IM, IS, LH) = kf_update(X,", "* pi) + 0.5 * log(det(S)) P = exp(-E) return (P[0],E[0]) from numpy", "function gauss_pdf. \"\"\" IM = dot(H, X) IS = R + dot(H, dot(P,", "import dot, sum, tile, linalg from numpy.linalg import inv def kf_predict(X, P, A,", "Predictive probability (likelihood) of measurement which is computed using the Python function gauss_pdf.", "[0.1]]) P = diag((0.01, 0.01, 0.01, 0.01)) A = array([[1, 0, dt ,", "Kalman Filter N_iter = 50 # Applying the Kalman Filter for i in", "== 1: DX = X - tile(M, X.shape()[1]) E = 0.5 * sum(DX", "mean state estimate of the previous step (k−1). P: The state covariance of", "log(det(S)) P = exp(-E) return (P[0],E[0]) from numpy import * from numpy.linalg import", "step of mobile movement dt = 0.1 # Initialization of state matrices X", "of previous step (k−1). A: The transition n × n matrix. Q: The", "pi) + 0.5 * log(det(S)) P = exp(-E) return (P[0],E[0]) from numpy import", "gauss_pdf(X, M, S): if M.shape()[1] == 1: DX = X - tile(M, X.shape()[1])", "of Y IS: the Covariance or predictive mean of Y LH: the Predictive", "kf_predict(X, P, A, Q, B, U): \"\"\" X: The mean state estimate of", "iterations in Kalman Filter N_iter = 50 # Applying the Kalman Filter for", "dot(A, X) + dot(B, U) P = dot(A, dot(P, A.T)) + Q return(X,P)", "M.shape()[1])- M E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0) E =", "P = exp(-E) return (P[0],E[0]) from numpy import * from numpy.linalg import inv", "P = exp(-E) elif X.shape()[1] == 1: DX = tile(X, M.shape()[1])- M E", "Q, B, U) (X, P, K, IM, IS, LH) = kf_update(X, P, Y,", "dt , 0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0,", "B: The input effect matrix. U: The control input. \"\"\" X = dot(A,", "= dot(H, X) IS = R + dot(H, dot(P, H.T)) K = dot(P,", "0, dt], [0, 0, 1, 0], [0, 0, 0, 1]]) Q = eye(X.shape()[0])", "[0.0], [0.1], [0.1]]) P = diag((0.01, 0.01, 0.01, 0.01)) A = array([[1, 0,", "abs(randn(1)[0])]]) H = array([[1, 0, 0, 0], [0, 1, 0, 0]]) R =", "Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices Y", "H, R) Y = array([[X[0,0] + abs(0.1 * randn(1)[0])],[X[1, 0] + abs(0.1 *", "M.shape()[1] == 1: DX = X - tile(M, X.shape()[1]) E = 0.5 *", "the Kalman Gain matrix IM: the Mean of predictive distribution of Y IS:", "dot(A, dot(P, A.T)) + Q return(X,P) def kf_update(X, P, Y, H, R): \"\"\"", "From http://arxiv.org/pdf/1204.0375.pdf \"\"\" from numpy import dot, sum, tile, linalg from numpy.linalg import", "The transition n × n matrix. Q: The process noise covariance matrix. B:", "import inv def kf_predict(X, P, A, Q, B, U): \"\"\" X: The mean", "using the Python function gauss_pdf. \"\"\" IM = dot(H, X) IS = R", "dot(DX.T, dot(inv(S), DX)) E = E + 0.5 * M.shape()[0] * log(2 *", "P - dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def", "= tile(X, M.shape()[1])- M E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0)", "from numpy import * from numpy.linalg import inv #time step of mobile movement", "X = array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01, 0.01, 0.01, 0.01)) A", "* pi) + 0.5 * log(det(S)) P = exp(-E) elif X.shape()[1] == 1:", "numpy.linalg import inv def kf_predict(X, P, A, Q, B, U): \"\"\" X: The", "tile, linalg from numpy.linalg import inv def kf_predict(X, P, A, Q, B, U):", "process noise covariance matrix. B: The input effect matrix. U: The control input.", "+ 0.5 * log(det(S)) P = exp(-E) return (P[0],E[0]) from numpy import *", "[0.1], [0.1]]) P = diag((0.01, 0.01, 0.01, 0.01)) A = array([[1, 0, dt", "0.1 # Initialization of state matrices X = array([[0.0], [0.0], [0.1], [0.1]]) P", "LH) = kf_update(X, P, Y, H, R) Y = array([[X[0,0] + abs(0.1 *", "array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01, 0.01, 0.01, 0.01)) A = array([[1,", "= dot(A, X) + dot(B, U) P = dot(A, dot(P, A.T)) + Q", "A, Q, B, U) (X, P, K, IM, IS, LH) = kf_update(X, P,", "of measurement which is computed using the Python function gauss_pdf. \"\"\" IM =", "def kf_predict(X, P, A, Q, B, U): \"\"\" X: The mean state estimate", "inv(IS))) X = X + dot(K, (Y-IM)) P = P - dot(K, dot(IS,", "X) + dot(B, U) P = dot(A, dot(P, A.T)) + Q return(X,P) def", "× n matrix. Q: The process noise covariance matrix. B: The input effect", "1, 0], [0, 0, 0, 1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U", "covariance of previous step (k−1). A: The transition n × n matrix. Q:", "0.5 * log(det(S)) P = exp(-E) elif X.shape()[1] == 1: DX = tile(X,", "covariance matrix. B: The input effect matrix. U: The control input. \"\"\" X", "The state covariance of previous step (k−1). A: The transition n × n", "H = array([[1, 0, 0, 0], [0, 1, 0, 0]]) R = eye(Y.shape()[0])", "previous step (k−1). P: The state covariance of previous step (k−1). A: The", "1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]]) Q =", "X = dot(A, X) + dot(B, U) P = dot(A, dot(P, A.T)) +", "A.T)) + Q return(X,P) def kf_update(X, P, Y, H, R): \"\"\" K: the", "Mean of predictive distribution of Y IS: the Covariance or predictive mean of", "control input. \"\"\" X = dot(A, X) + dot(B, U) P = dot(A,", "R = eye(Y.shape()[0]) # Number of iterations in Kalman Filter N_iter = 50", "log(det(S)) P = exp(-E) else: DX = X-M E = 0.5 * dot(DX.T,", "dt = 0.1 # Initialization of state matrices X = array([[0.0], [0.0], [0.1],", "in arange(0, N_iter): (X, P) = kf_predict(X, P, A, Q, B, U) (X,", "== 1: DX = tile(X, M.shape()[1])- M E = 0.5 * sum(DX *", "Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0, 0,", "X-M E = 0.5 * dot(DX.T, dot(inv(S), DX)) E = E + 0.5", "K, IM, IS, LH) = kf_update(X, P, Y, H, R) Y = array([[X[0,0]", "* log(det(S)) P = exp(-E) else: DX = X-M E = 0.5 *", "1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices", "of mobile movement dt = 0.1 # Initialization of state matrices X =", "P) = kf_predict(X, P, A, Q, B, U) (X, P, K, IM, IS,", "= exp(-E) else: DX = X-M E = 0.5 * dot(DX.T, dot(inv(S), DX))", "* pi) + 0.5 * log(det(S)) P = exp(-E) else: DX = X-M", "U): \"\"\" X: The mean state estimate of the previous step (k−1). P:", "of Y LH: the Predictive probability (likelihood) of measurement which is computed using", "M.shape()[0] * log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) return", "P, Y, H, R): \"\"\" K: the Kalman Gain matrix IM: the Mean", "= 50 # Applying the Kalman Filter for i in arange(0, N_iter): (X,", "log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) return (P[0],E[0]) from", "E = 0.5 * dot(DX.T, dot(inv(S), DX)) E = E + 0.5 *", "* log(det(S)) P = exp(-E) elif X.shape()[1] == 1: DX = tile(X, M.shape()[1])-", "inv def kf_predict(X, P, A, Q, B, U): \"\"\" X: The mean state", "matrix. B: The input effect matrix. U: The control input. \"\"\" X =", "+ dot(B, U) P = dot(A, dot(P, A.T)) + Q return(X,P) def kf_update(X,", "predictive mean of Y LH: the Predictive probability (likelihood) of measurement which is", "+ dot(H, dot(P, H.T)) K = dot(P, dot(H.T, inv(IS))) X = X +", "0, 1]]) Q = eye(X.shape()[0]) B = eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement", "inv #time step of mobile movement dt = 0.1 # Initialization of state", "input effect matrix. U: The control input. \"\"\" X = dot(A, X) +", "matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0,", "H.T)) K = dot(P, dot(H.T, inv(IS))) X = X + dot(K, (Y-IM)) P", "eye(Y.shape()[0]) # Number of iterations in Kalman Filter N_iter = 50 # Applying", "The process noise covariance matrix. B: The input effect matrix. U: The control", "= P - dot(K, dot(IS, K.T)) LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH)", "DX = X-M E = 0.5 * dot(DX.T, dot(inv(S), DX)) E = E", "Initialization of state matrices X = array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01,", "if M.shape()[1] == 1: DX = X - tile(M, X.shape()[1]) E = 0.5", "K: the Kalman Gain matrix IM: the Mean of predictive distribution of Y", "= R + dot(H, dot(P, H.T)) K = dot(P, dot(H.T, inv(IS))) X =", "movement dt = 0.1 # Initialization of state matrices X = array([[0.0], [0.0],", "= X - tile(M, X.shape()[1]) E = 0.5 * sum(DX * (dot(inv(S), DX)),", "of the previous step (k−1). P: The state covariance of previous step (k−1).", "eye(X.shape()[0]) U = zeros((X.shape()[0],1)) # Measurement matrices Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0]", "the previous step (k−1). P: The state covariance of previous step (k−1). A:", "Gain matrix IM: the Mean of predictive distribution of Y IS: the Covariance", "* (dot(inv(S), DX)), axis=0) E = E + 0.5 * M.shape()[0] * log(2", "0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S)) P =", "[0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]]) Q", "for i in arange(0, N_iter): (X, P) = kf_predict(X, P, A, Q, B,", "LH: the Predictive probability (likelihood) of measurement which is computed using the Python", "linalg from numpy.linalg import inv def kf_predict(X, P, A, Q, B, U): \"\"\"", "DX = X - tile(M, X.shape()[1]) E = 0.5 * sum(DX * (dot(inv(S),", "+ abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]]) H = array([[1, 0, 0, 0], [0, 1,", "of predictive distribution of Y IS: the Covariance or predictive mean of Y", "def gauss_pdf(X, M, S): if M.shape()[1] == 1: DX = X - tile(M,", "mean of Y LH: the Predictive probability (likelihood) of measurement which is computed", "N_iter): (X, P) = kf_predict(X, P, A, Q, B, U) (X, P, K,", "* log(det(S)) P = exp(-E) return (P[0],E[0]) from numpy import * from numpy.linalg", "the Mean of predictive distribution of Y IS: the Covariance or predictive mean", "return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1] == 1: DX = X", "the Kalman Filter for i in arange(0, N_iter): (X, P) = kf_predict(X, P,", "\"\"\" K: the Kalman Gain matrix IM: the Mean of predictive distribution of", "(X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1] == 1: DX = X -", "K.T)) LH = gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if", "state estimate of the previous step (k−1). P: The state covariance of previous", "= gauss_pdf(Y, IM, IS) return (X,P,K,IM,IS,LH) def gauss_pdf(X, M, S): if M.shape()[1] ==", "log(2 * pi) + 0.5 * log(det(S)) P = exp(-E) elif X.shape()[1] ==", "state matrices X = array([[0.0], [0.0], [0.1], [0.1]]) P = diag((0.01, 0.01, 0.01," ]
[ "import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError: long_description", "packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming", "install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming Language", "utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try:", "# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here", "from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except", "long_description = open(\"README.md\").read() except IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\",", "os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\",", "long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\",", "\"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming Language :: Python", "\"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming Language :: Python ::", "setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError: long_description =", "], long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming Language :: Python :: 3.6\",", "open(\"README.md\").read() except IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\",", "import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description =", "setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError:", "\"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\",", "name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description,", "license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language ::", "setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ],", "version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[", "classifiers=[ \"Programming Language :: Python\", \"Programming Language :: Python :: 3.6\", ], )", "= open(\"README.md\").read() except IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\",", "= \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\",", "long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming Language :: Python :: 3.6\", ],", "find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError: long_description = \"\"", "IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[", "-*- coding: utf-8 -*- import os from setuptools import setup, find_packages here =", "description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming", "author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language :: Python\",", "\"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language :: Python\", \"Programming Language ::", "here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError: long_description = \"\" setup(", "-*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description", "coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__))", "os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read()", "= os.path.abspath(os.path.dirname(__file__)) try: long_description = open(\"README.md\").read() except IOError: long_description = \"\" setup( name=\"word-embedder\",", "try: long_description = open(\"README.md\").read() except IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word", "except IOError: long_description = \"\" setup( name=\"word-embedder\", version=\"1.0.0\", description=\"Word Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(),", "Embedder\", license=\"MIT\", author=\"Solumilken\", packages=find_packages(), install_requires=[ \"mkdir-p>=0.1.1\", \"numpy>=1.15.1\", \"python-dotenv==0.9.1\", ], long_description=long_description, classifiers=[ \"Programming Language" ]
[ "the fractions of: - lost (categorized by us) respondents who claim to have", "users: users DataFrame, as returned by get_user_totals() :param win_survey: windows survey result, as", "which eligible users (i.e. those who are Python coders who use a Kite-supported", "motivation behind finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of", "dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df:", "of it is that we want to find out the rate at which", "survey respondents who claim to have used Python but not Kite within the", "= dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame)", "rate based entirely on the kite_status data :param df: a DataFrame containing user", "that it may count ineligible users, or issues with collecting metrics). To fix", "- lost (categorized by us) respondents who claim to have used Python but", "len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started -", "to have used Python but not Kite within the past <active_days> (dormant_active_rate) We", "/ len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active + (df.dormant *", "dormant_lost_rate) + (df.lost * lost_lost_rate) return active / (active + churned) return retention_fn", "= active_users / (active_users + churned_users) :param histories: user history DataFrame, as returned", "active_choices = {'14', '30'} elif active_days == 90: active_choices = {'14', '30', '90'}", "(resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate =", "def retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active + (df.dormant * dormant_active_rate) +", "the retention rate \"\"\" # determine what are the responses to the \"last", "begin with the assumption that when looking at just the numbers from kite_status", "face value. We then calculate the fractions of: - lost (categorized by us)", "\"n\" in \"n-day active\") :return: a function that operates on a DataFrame containing", "using the assumption that this rate holds for every measured cohort. active_users =", "of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the last", "apply corrections to the retention rate by redistributing our lost and dormant users", "have used both Kite and Python within the past <active_days> (lost_active_rate) - dormant", "respondents who answered both of the \"last used Kite\"/ \"last used Python\" questions", "active_days == 30: active_choices = {'14', '30'} elif active_days == 90: active_choices =", "about the last time a user coded in Python and the last time", "<active_days> (dormant_lost_rate) - dormant (categorized by us) survey respondents who claim to have", "for every measured cohort. active_users = active_count + (dormant_count * dormant_active_rate) + (lost_count", "14: active_choices = {'14'} elif active_days == 30: active_choices = {'14', '30'} elif", "this, we look at the results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This", "user counts for the following columns - [unactivated, activate, lost, dormant] and returns", "that when looking at just the numbers from kite_status events, our categorization of", "who use a Kite-supported editor) retain. To achieve this, we begin with the", "coded in Python and the last time a user coded using Kite. From", "user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the last time a user", "{'14'} elif active_days == 30: active_choices = {'14', '30'} elif active_days == 90:", "who are Python coders who use a Kite-supported editor) retain. To achieve this,", "needs to be in {14,30,90}\") # we only consider respondents who answered both", ":param histories: user history DataFrame, as returned by load_user_histories() :param users: users DataFrame,", "past <active_days> (dormant_lost_rate) - dormant (categorized by us) survey respondents who claim to", "{'14', '30'} elif active_days == 90: active_choices = {'14', '30', '90'} else: raise", "...but the gist of it is that we want to find out the", "issues with collecting metrics). To fix this, we look at the results of", "have used Python but not Kite within the past <active_days> (lost_lost_rate) - lost", "* lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate =", "/ len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps)", "* lost_lost_rate) true_retention_rate = active_users / (active_users + churned_users) :param histories: user history", "history DataFrame, as returned by load_user_histories() :param users: users DataFrame, as returned by", "lost (categorized by us) respondents who claim to have used Python but not", "a Kite-supported editor) retain. To achieve this, we begin with the assumption that", "[unactivated, activate, lost, dormant] and returns a series containing just one column with", "- lost (categorized by us) survey respondents who claim to have used both", "this rate holds for every measured cohort. active_users = active_count + (dormant_count *", "by cohort (e.g. as returned by counts_for_daily_cohort()) For the motivation behind finding the", "* dormant_active_rate) + (df.lost * lost_active_rate) churned = (df.dormant * dormant_lost_rate) + (df.lost", "time a user coded using Kite. From these we can determine whether a", "the \"last used Kite\"/ \"last used Python\" questions resps = win_survey[(win_survey.last_used_kite != '')", "lost_active_rate = len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate =", "rate \"\"\" # determine what are the responses to the \"last used Kite\"", "& (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate", "churned = (df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate) return active / (active", "determine what are the responses to the \"last used Kite\" / \"last used", "last time a user coded using Kite. From these we can determine whether", "returned by windows_survey.get_responses() :param active_days: the active-day definition (the \"n\" in \"n-day active\")", "len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) /", "that operates on a DataFrame containing user counts for the following columns -", "of daily user counts by cohort (e.g. as returned by counts_for_daily_cohort()) For the", "lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices)", "the retention rate by redistributing our lost and dormant users according to these", "fact that it may count ineligible users, or issues with collecting metrics). To", "= len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event", "then calculate the fractions of: - lost (categorized by us) respondents who claim", "(active_users + churned_users) :param histories: user history DataFrame, as returned by load_user_histories() :param", "+ (df.dormant * dormant_active_rate) + (df.lost * lost_active_rate) churned = (df.dormant * dormant_lost_rate)", "rate for each row \"\"\" return df.active / (df.active + df.lost + df.dormant)", "= resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active", "= {'14', '30'} elif active_days == 90: active_choices = {'14', '30', '90'} else:", "lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) &", "same index as df, containing the calculated retention rate for each row \"\"\"", "incorrect (due to the fact that it may count ineligible users, or issues", "of dormant and lost users may be incorrect (due to the fact that", "rate by redistributing our lost and dormant users according to these calculated rates,", "This survey includes questions about the last time a user coded in Python", "returned by counts_for_daily_cohort() :return: a Series, with the same index as df, containing", "within the past <active_days> (lost_active_rate) - dormant (categorized by us) survey respondents who", "- datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps)", "< resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active)", "counts for the following columns - [unactivated, activate, lost, dormant] and returns a", "we can determine whether a user is truly lost or dormant, at least", "-> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that can calculate the \"true retention\"", "user # is still using Kite/Python within the desired window if active_days ==", "Returns a function that can calculate the \"true retention\" rate given a DataFrame", "naive retention rate based entirely on the kite_status data :param df: a DataFrame", "-> pd.Series: \"\"\" Calculates naive retention rate based entirely on the kite_status data", "the past <active_days> (dormant_lost_rate) - dormant (categorized by us) survey respondents who claim", "index as df, containing the calculated retention rate for each row \"\"\" return", "cohort (e.g. as returned by counts_for_daily_cohort()) For the motivation behind finding the true", "= (df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate) return active / (active +", "columns - [unactivated, activate, lost, dormant] and returns a series containing just one", "Series, with the same index as df, containing the calculated retention rate for", "datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost", "true_retention_rate = active_users / (active_users + churned_users) :param histories: user history DataFrame, as", "\"\"\" Returns a function that can calculate the \"true retention\" rate given a", "active = df.active + (df.dormant * dormant_active_rate) + (df.lost * lost_active_rate) churned =", "dormant (categorized by us) survey respondents who claim to have used Python but", "Kite and Python within the past <active_days> (lost_active_rate) - dormant (categorized by us)", "by counts_for_daily_cohort()) For the motivation behind finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users", "df, containing the calculated retention rate for each row \"\"\" return df.active /", "return df.active / (df.active + df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days:", "(dormant_active_rate) We then apply corrections to the retention rate by redistributing our lost", "retention rate by redistributing our lost and dormant users according to these calculated", "questions that indicate the user # is still using Kite/Python within the desired", "function that can calculate the \"true retention\" rate given a DataFrame of daily", "resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) /", "but not Kite within the past <active_days> (dormant_lost_rate) - dormant (categorized by us)", "* lost_active_rate) churned = (df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate) return active", "containing user counts for the following columns - [unactivated, activate, lost, dormant] and", "column with the retention rate \"\"\" # determine what are the responses to", "~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series:", "the past <active_days> (lost_lost_rate) - lost (categorized by us) survey respondents who claim", "- dormant (categorized by us) survey respondents who claim to have used Python", "resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day <", "retention\" rate given a DataFrame of daily user counts by cohort (e.g. as", "lost_active_rate) churned = (df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate) return active /", "lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)]", "df: a DataFrame containing user counts for the following columns - [unactivated, activate,", "/ (active_users + churned_users) :param histories: user history DataFrame, as returned by load_user_histories()", "true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is that we", "rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is that we want to", "to have used Python but not Kite within the past <active_days> (lost_lost_rate) -", "what are the responses to the \"last used Kite\" / \"last used Python\"", "the fact that it may count ineligible users, or issues with collecting metrics).", ">= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[", "To fix this, we look at the results of the Windows user survey:", "of: - lost (categorized by us) respondents who claim to have used Python", "or issues with collecting metrics). To fix this, we look at the results", "as returned by get_user_totals() :param win_survey: windows survey result, as returned by windows_survey.get_responses()", "by load_user_histories() :param users: users DataFrame, as returned by get_user_totals() :param win_survey: windows", "respondents who claim to have used Python but not Kite within the past", "a DataFrame of daily user counts by cohort (e.g. as returned by counts_for_daily_cohort())", "value. We then calculate the fractions of: - lost (categorized by us) respondents", "& lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)]", "it may count ineligible users, or issues with collecting metrics). To fix this,", "when looking at just the numbers from kite_status events, our categorization of dormant", "series containing just one column with the retention rate \"\"\" # determine what", "but not Kite within the past <active_days> (dormant_active_rate) We then apply corrections to", "pd.Series]: \"\"\" Returns a function that can calculate the \"true retention\" rate given", "least if we take that user's survey responses at face value. We then", "these we can determine whether a user is truly lost or dormant, at", "retention rate based entirely on the kite_status data :param df: a DataFrame containing", "dormant] - e.g. as returned by counts_for_daily_cohort() :return: a Series, with the same", "both of the \"last used Kite\"/ \"last used Python\" questions resps = win_survey[(win_survey.last_used_kite", "rate holds for every measured cohort. active_users = active_count + (dormant_count * dormant_active_rate)", "= resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate", "len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps", "users may be incorrect (due to the fact that it may count ineligible", "survey includes questions about the last time a user coded in Python and", "Kite. From these we can determine whether a user is truly lost or", "a user is truly lost or dormant, at least if we take that", "+ (lost_count * lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate)", "win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that can", ":param users: users DataFrame, as returned by get_user_totals() :param win_survey: windows survey result,", "the user # is still using Kite/Python within the desired window if active_days", "- datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps)", "to have used Python but not Kite within the past <active_days> (dormant_lost_rate) -", "still using Kite/Python within the desired window if active_days == 14: active_choices =", "by us) respondents who claim to have used Python but not Kite within", "win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day < resps.started -", "\"true retention\" rate given a DataFrame of daily user counts by cohort (e.g.", "from kite_status events, our categorization of dormant and lost users may be incorrect", "questions about the last time a user coded in Python and the last", "containing the calculated retention rate for each row \"\"\" return df.active / (df.active", "+ df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns", "lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate = active_users", "== 30: active_choices = {'14', '30'} elif active_days == 90: active_choices = {'14',", "elif active_days == 90: active_choices = {'14', '30', '90'} else: raise ValueError(\"active_days needs", "whether a user is truly lost or dormant, at least if we take", "From these we can determine whether a user is truly lost or dormant,", "= {'14', '30', '90'} else: raise ValueError(\"active_days needs to be in {14,30,90}\") #", "the motivation behind finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist", "churned_users) :param histories: user history DataFrame, as returned by load_user_histories() :param users: users", "rates, using the assumption that this rate holds for every measured cohort. active_users", "looking at just the numbers from kite_status events, our categorization of dormant and", "\"\"\" Calculates naive retention rate based entirely on the kite_status data :param df:", "(df.dormant * dormant_active_rate) + (df.lost * lost_active_rate) churned = (df.dormant * dormant_lost_rate) +", "<active_days> (lost_active_rate) - dormant (categorized by us) survey respondents who claim to have", "(df.active + df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame],", "measured cohort. active_users = active_count + (dormant_count * dormant_active_rate) + (lost_count * lost_active_rate)", "if active_days == 14: active_choices = {'14'} elif active_days == 30: active_choices =", "within the desired window if active_days == 14: active_choices = {'14'} elif active_days", "\"last used Python\" questions resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')]", "every measured cohort. active_users = active_count + (dormant_count * dormant_active_rate) + (lost_count *", "& (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active =", "= len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active +", "according to these calculated rates, using the assumption that this rate holds for", "to find out the rate at which eligible users (i.e. those who are", "the same index as df, containing the calculated retention rate for each row", "used Python but not Kite within the past <active_days> (dormant_lost_rate) - dormant (categorized", "df.active + (df.dormant * dormant_active_rate) + (df.lost * lost_active_rate) churned = (df.dormant *", "as df, containing the calculated retention rate for each row \"\"\" return df.active", "using Kite. From these we can determine whether a user is truly lost", "activate, lost, dormant] and returns a series containing just one column with the", "user coded in Python and the last time a user coded using Kite.", "not Kite within the past <active_days> (dormant_lost_rate) - dormant (categorized by us) survey", "= {'14'} elif active_days == 30: active_choices = {'14', '30'} elif active_days ==", "https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the last time a user coded in", "claim to have used Python but not Kite within the past <active_days> (dormant_lost_rate)", "- datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) &", "we begin with the assumption that when looking at just the numbers from", "us) respondents who claim to have used Python but not Kite within the", "that indicate the user # is still using Kite/Python within the desired window", "user counts for the following columns - [unactivated, activate, lost, dormant] - e.g.", "a series containing just one column with the retention rate \"\"\" # determine", "(dormant_lost_rate) - dormant (categorized by us) survey respondents who claim to have used", "the desired window if active_days == 14: active_choices = {'14'} elif active_days ==", "events, our categorization of dormant and lost users may be incorrect (due to", ":return: a Series, with the same index as df, containing the calculated retention", "and returns a series containing just one column with the retention rate \"\"\"", "- e.g. as returned by counts_for_daily_cohort() :return: a Series, with the same index", "# we only consider respondents who answered both of the \"last used Kite\"/", "(categorized by us) survey respondents who claim to have used both Kite and", "counts_for_daily_cohort() :return: a Series, with the same index as df, containing the calculated", "active_days == 90: active_choices = {'14', '30', '90'} else: raise ValueError(\"active_days needs to", "each row \"\"\" return df.active / (df.active + df.lost + df.dormant) def true_retention_fn(", "those who are Python coders who use a Kite-supported editor) retain. To achieve", "at which eligible users (i.e. those who are Python coders who use a", "by get_user_totals() :param win_survey: windows survey result, as returned by windows_survey.get_responses() :param active_days:", "counts_for_daily_cohort()) For the motivation behind finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but", "used Python but not Kite within the past <active_days> (lost_lost_rate) - lost (categorized", "who answered both of the \"last used Kite\"/ \"last used Python\" questions resps", "respondents who claim to have used both Kite and Python within the past", "len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active + (df.dormant", "def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention rate based entirely on", "90: active_choices = {'14', '30', '90'} else: raise ValueError(\"active_days needs to be in", "Kite within the past <active_days> (lost_lost_rate) - lost (categorized by us) survey respondents", "pd.DataFrame) -> pd.Series: active = df.active + (df.dormant * dormant_active_rate) + (df.lost *", "'30', '90'} else: raise ValueError(\"active_days needs to be in {14,30,90}\") # we only", "to the \"last used Kite\" / \"last used Python\" questions that indicate the", "len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def", "count ineligible users, or issues with collecting metrics). To fix this, we look", "assumption that this rate holds for every measured cohort. active_users = active_count +", "for each row \"\"\" return df.active / (df.active + df.lost + df.dormant) def", "cohort. active_users = active_count + (dormant_count * dormant_active_rate) + (lost_count * lost_active_rate) churned_users", "can calculate the \"true retention\" rate given a DataFrame of daily user counts", "= len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost)", "= active_count + (dormant_count * dormant_active_rate) + (lost_count * lost_active_rate) churned_users = (dormant_count", "on a DataFrame containing user counts for the following columns - [unactivated, activate,", "a user coded in Python and the last time a user coded using", "Python and the last time a user coded using Kite. From these we", "\"last used Kite\" / \"last used Python\" questions that indicate the user #", "to have used both Kite and Python within the past <active_days> (lost_active_rate) -", "= lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost = lost_resps[", "Kite within the past <active_days> (dormant_lost_rate) - dormant (categorized by us) survey respondents", "ValueError(\"active_days needs to be in {14,30,90}\") # we only consider respondents who answered", "+ df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]:", "coded using Kite. From these we can determine whether a user is truly", "histories: user history DataFrame, as returned by load_user_histories() :param users: users DataFrame, as", "just one column with the retention rate \"\"\" # determine what are the", "the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the last time", "(df.lost * lost_active_rate) churned = (df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate) return", "responses at face value. We then calculate the fractions of: - lost (categorized", "retention rate \"\"\" # determine what are the responses to the \"last used", "desired window if active_days == 14: active_choices = {'14'} elif active_days == 30:", "Kite within the past <active_days> (dormant_active_rate) We then apply corrections to the retention", "(lost_lost_rate) - lost (categorized by us) survey respondents who claim to have used", "at the results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions", "includes questions about the last time a user coded in Python and the", "Kite-supported editor) retain. To achieve this, we begin with the assumption that when", "claim to have used both Kite and Python within the past <active_days> (lost_active_rate)", "dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices)", "following columns - [unactivated, activate, lost, dormant] and returns a series containing just", "and dormant users according to these calculated rates, using the assumption that this", "users according to these calculated rates, using the assumption that this rate holds", "active_choices = {'14', '30', '90'} else: raise ValueError(\"active_days needs to be in {14,30,90}\")", "in Python and the last time a user coded using Kite. From these", "find out the rate at which eligible users (i.e. those who are Python", "the active-day definition (the \"n\" in \"n-day active\") :return: a function that operates", "Kite\" / \"last used Python\" questions that indicate the user # is still", "windows_survey.get_responses() :param active_days: the active-day definition (the \"n\" in \"n-day active\") :return: a", "only consider respondents who answered both of the \"last used Kite\"/ \"last used", "# determine what are the responses to the \"last used Kite\" / \"last", "our categorization of dormant and lost users may be incorrect (due to the", "(e.g. as returned by counts_for_daily_cohort()) For the motivation behind finding the true retention", "lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost =", "/ (df.active + df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int) ->", "for the following columns - [unactivated, activate, lost, dormant] and returns a series", "len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) /", "* dormant_active_rate) + (lost_count * lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) + (lost_count", "columns - [unactivated, activate, lost, dormant] - e.g. as returned by counts_for_daily_cohort() :return:", "by redistributing our lost and dormant users according to these calculated rates, using", "claim to have used Python but not Kite within the past <active_days> (dormant_active_rate)", "or dormant, at least if we take that user's survey responses at face", "categorization of dormant and lost users may be incorrect (due to the fact", "within the past <active_days> (dormant_lost_rate) - dormant (categorized by us) survey respondents who", "these calculated rates, using the assumption that this rate holds for every measured", "to be in {14,30,90}\") # we only consider respondents who answered both of", "as returned by counts_for_daily_cohort()) For the motivation behind finding the true retention rate,", "past <active_days> (lost_active_rate) - dormant (categorized by us) survey respondents who claim to", "- [unactivated, activate, lost, dormant] and returns a series containing just one column", "past <active_days> (dormant_active_rate) We then apply corrections to the retention rate by redistributing", "Calculates naive retention rate based entirely on the kite_status data :param df: a", "naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention rate based entirely on the", "entirely on the kite_status data :param df: a DataFrame containing user counts for", "containing user counts for the following columns - [unactivated, activate, lost, dormant] -", "not Kite within the past <active_days> (dormant_active_rate) We then apply corrections to the", "a DataFrame containing user counts for the following columns - [unactivated, activate, lost,", "lost_lost_rate) true_retention_rate = active_users / (active_users + churned_users) :param histories: user history DataFrame,", "retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is that we want", "are Python coders who use a Kite-supported editor) retain. To achieve this, we", "active-day definition (the \"n\" in \"n-day active\") :return: a function that operates on", "datetime import pandas as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive", "answered both of the \"last used Kite\"/ \"last used Python\" questions resps =", "= len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost)", "that we want to find out the rate at which eligible users (i.e.", "dormant users according to these calculated rates, using the assumption that this rate", "* dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate = active_users / (active_users + churned_users)", "DataFrame containing user counts for the following columns - [unactivated, activate, lost, dormant]", "fractions of: - lost (categorized by us) respondents who claim to have used", "= lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day", "resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active =", "survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the last time a user coded", "corrections to the retention rate by redistributing our lost and dormant users according", "lost, dormant] and returns a series containing just one column with the retention", "Python\" questions that indicate the user # is still using Kite/Python within the", "Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that can calculate the \"true retention\" rate", "returned by get_user_totals() :param win_survey: windows survey result, as returned by windows_survey.get_responses() :param", "consider respondents who answered both of the \"last used Kite\"/ \"last used Python\"", "typing import Callable import datetime import pandas as pd def naive_retention_fn(df: pd.DataFrame) ->", "lost (categorized by us) survey respondents who claim to have used both Kite", "behind finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it", "calculated retention rate for each row \"\"\" return df.active / (df.active + df.lost", "the following columns - [unactivated, activate, lost, dormant] - e.g. as returned by", "is that we want to find out the rate at which eligible users", "active_users / (active_users + churned_users) :param histories: user history DataFrame, as returned by", "be incorrect (due to the fact that it may count ineligible users, or", "lost and dormant users according to these calculated rates, using the assumption that", "eligible users (i.e. those who are Python coders who use a Kite-supported editor)", "30: active_choices = {'14', '30'} elif active_days == 90: active_choices = {'14', '30',", "by windows_survey.get_responses() :param active_days: the active-day definition (the \"n\" in \"n-day active\") :return:", "+ (lost_count * lost_lost_rate) true_retention_rate = active_users / (active_users + churned_users) :param histories:", "'30'} elif active_days == 90: active_choices = {'14', '30', '90'} else: raise ValueError(\"active_days", "~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started", "& dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)]", "else: raise ValueError(\"active_days needs to be in {14,30,90}\") # we only consider respondents", "-> pd.Series: active = df.active + (df.dormant * dormant_active_rate) + (df.lost * lost_active_rate)", "activate, lost, dormant] - e.g. as returned by counts_for_daily_cohort() :return: a Series, with", "we only consider respondents who answered both of the \"last used Kite\"/ \"last", "== 14: active_choices = {'14'} elif active_days == 30: active_choices = {'14', '30'}", "DataFrame of daily user counts by cohort (e.g. as returned by counts_for_daily_cohort()) For", "the numbers from kite_status events, our categorization of dormant and lost users may", "'')] lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) &", "look at the results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes", "that can calculate the \"true retention\" rate given a DataFrame of daily user", "at just the numbers from kite_status events, our categorization of dormant and lost", "(lost_count * lost_lost_rate) true_retention_rate = active_users / (active_users + churned_users) :param histories: user", "Python within the past <active_days> (lost_active_rate) - dormant (categorized by us) survey respondents", "dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost =", "!= '')] lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices)", "Kite/Python within the desired window if active_days == 14: active_choices = {'14'} elif", "https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is that we want to find out", "not Kite within the past <active_days> (lost_lost_rate) - lost (categorized by us) survey", "have used Python but not Kite within the past <active_days> (dormant_active_rate) We then", "indicate the user # is still using Kite/Python within the desired window if", ":param active_days: the active-day definition (the \"n\" in \"n-day active\") :return: a function", "claim to have used Python but not Kite within the past <active_days> (lost_lost_rate)", "row \"\"\" return df.active / (df.active + df.lost + df.dormant) def true_retention_fn( win_survey:", "df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\"", "<filename>kite-python/kite_ml/kite/exp/eligible_users/retention_rate.py<gh_stars>10-100 from typing import Callable import datetime import pandas as pd def naive_retention_fn(df:", "can determine whether a user is truly lost or dormant, at least if", "that user's survey responses at face value. We then calculate the fractions of:", "(i.e. those who are Python coders who use a Kite-supported editor) retain. To", "Python but not Kite within the past <active_days> (lost_lost_rate) - lost (categorized by", "We then calculate the fractions of: - lost (categorized by us) respondents who", "& lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started -", "the last time a user coded in Python and the last time a", "as returned by counts_for_daily_cohort() :return: a Series, with the same index as df,", "true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that", "to the retention rate by redistributing our lost and dormant users according to", "used Kite\"/ \"last used Python\" questions resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py", "(due to the fact that it may count ineligible users, or issues with", "pandas as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention rate", "dormant_active_rate) + (df.lost * lost_active_rate) churned = (df.dormant * dormant_lost_rate) + (df.lost *", "active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that can calculate the", "Python but not Kite within the past <active_days> (dormant_active_rate) We then apply corrections", "(win_survey.last_used_py != '')] lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[", "\"last used Python\" questions that indicate the user # is still using Kite/Python", "Python coders who use a Kite-supported editor) retain. To achieve this, we begin", "out the rate at which eligible users (i.e. those who are Python coders", "questions resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day", "in {14,30,90}\") # we only consider respondents who answered both of the \"last", "operates on a DataFrame containing user counts for the following columns - [unactivated,", "the past <active_days> (dormant_active_rate) We then apply corrections to the retention rate by", "= df.active + (df.dormant * dormant_active_rate) + (df.lost * lost_active_rate) churned = (df.dormant", "df.active / (df.active + df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int)", "dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active =", "lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days))", "used Python but not Kite within the past <active_days> (dormant_active_rate) We then apply", "who claim to have used Python but not Kite within the past <active_days>", "the last time a user coded using Kite. From these we can determine", "active\") :return: a function that operates on a DataFrame containing user counts for", "but not Kite within the past <active_days> (lost_lost_rate) - lost (categorized by us)", "= win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day < resps.started", "the responses to the \"last used Kite\" / \"last used Python\" questions that", "retention rate for each row \"\"\" return df.active / (df.active + df.lost +", "pd.Series: \"\"\" Calculates naive retention rate based entirely on the kite_status data :param", "kite_status data :param df: a DataFrame containing user counts for the following columns", "definition (the \"n\" in \"n-day active\") :return: a function that operates on a", "To achieve this, we begin with the assumption that when looking at just", "a function that operates on a DataFrame containing user counts for the following", "lost, dormant] - e.g. as returned by counts_for_daily_cohort() :return: a Series, with the", "retain. To achieve this, we begin with the assumption that when looking at", "* dormant_lost_rate) + (df.lost * lost_lost_rate) return active / (active + churned) return", "and Python within the past <active_days> (lost_active_rate) - dormant (categorized by us) survey", "we take that user's survey responses at face value. We then calculate the", "dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))]", "dormant_active_rate) + (lost_count * lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) + (lost_count *", "user is truly lost or dormant, at least if we take that user's", "calculate the fractions of: - lost (categorized by us) respondents who claim to", "retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active + (df.dormant * dormant_active_rate) + (df.lost", "gist of it is that we want to find out the rate at", "and lost users may be incorrect (due to the fact that it may", "the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is that", "at face value. We then calculate the fractions of: - lost (categorized by", "user history DataFrame, as returned by load_user_histories() :param users: users DataFrame, as returned", "as returned by windows_survey.get_responses() :param active_days: the active-day definition (the \"n\" in \"n-day", "who claim to have used both Kite and Python within the past <active_days>", "truly lost or dormant, at least if we take that user's survey responses", "int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that can calculate the \"true", "within the past <active_days> (dormant_active_rate) We then apply corrections to the retention rate", "in \"n-day active\") :return: a function that operates on a DataFrame containing user", "returned by load_user_histories() :param users: users DataFrame, as returned by get_user_totals() :param win_survey:", "load_user_histories() :param users: users DataFrame, as returned by get_user_totals() :param win_survey: windows survey", "assumption that when looking at just the numbers from kite_status events, our categorization", "a Series, with the same index as df, containing the calculated retention rate", "dormant] and returns a series containing just one column with the retention rate", "pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention rate based entirely", "lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps =", "ineligible users, or issues with collecting metrics). To fix this, we look at", "Kite\"/ \"last used Python\" questions resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py !=", "pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention rate based entirely on the kite_status", "past <active_days> (lost_lost_rate) - lost (categorized by us) survey respondents who claim to", "the \"last used Kite\" / \"last used Python\" questions that indicate the user", "(categorized by us) respondents who claim to have used Python but not Kite", "editor) retain. To achieve this, we begin with the assumption that when looking", "coders who use a Kite-supported editor) retain. To achieve this, we begin with", "active_count + (dormant_count * dormant_active_rate) + (lost_count * lost_active_rate) churned_users = (dormant_count *", "on the kite_status data :param df: a DataFrame containing user counts for the", "counts by cohort (e.g. as returned by counts_for_daily_cohort()) For the motivation behind finding", "result, as returned by windows_survey.get_responses() :param active_days: the active-day definition (the \"n\" in", "- [unactivated, activate, lost, dormant] - e.g. as returned by counts_for_daily_cohort() :return: a", "active_days: the active-day definition (the \"n\" in \"n-day active\") :return: a function that", "rate at which eligible users (i.e. those who are Python coders who use", "{14,30,90}\") # we only consider respondents who answered both of the \"last used", "dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate =", "For the motivation behind finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the", "the assumption that when looking at just the numbers from kite_status events, our", "resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate =", "len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event <", "take that user's survey responses at face value. We then calculate the fractions", "finding the true retention rate, see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is", "see: https://kite.quip.com/TJxqAJs7vz05/Eligible-Users ...but the gist of it is that we want to find", "survey result, as returned by windows_survey.get_responses() :param active_days: the active-day definition (the \"n\"", "users (i.e. those who are Python coders who use a Kite-supported editor) retain.", "users, or issues with collecting metrics). To fix this, we look at the", "of the \"last used Kite\"/ \"last used Python\" questions resps = win_survey[(win_survey.last_used_kite !=", "Python but not Kite within the past <active_days> (dormant_lost_rate) - dormant (categorized by", "Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the last time a", "\"n-day active\") :return: a function that operates on a DataFrame containing user counts", "have used Python but not Kite within the past <active_days> (dormant_lost_rate) - dormant", "resps.started - datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) /", "churned_users = (dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate = active_users /", "active_days == 14: active_choices = {'14'} elif active_days == 30: active_choices = {'14',", "lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) &", "used Kite\" / \"last used Python\" questions that indicate the user # is", "want to find out the rate at which eligible users (i.e. those who", "kite_status events, our categorization of dormant and lost users may be incorrect (due", "import datetime import pandas as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates", "/ \"last used Python\" questions that indicate the user # is still using", "/ len(lost_resps) dormant_resps = resps[(resps.last_day >= resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started", "pd.Series: active = df.active + (df.dormant * dormant_active_rate) + (df.lost * lost_active_rate) churned", "by us) survey respondents who claim to have used both Kite and Python", "with collecting metrics). To fix this, we look at the results of the", "the kite_status data :param df: a DataFrame containing user counts for the following", "user counts by cohort (e.g. as returned by counts_for_daily_cohort()) For the motivation behind", "data :param df: a DataFrame containing user counts for the following columns -", "the rate at which eligible users (i.e. those who are Python coders who", "survey responses at face value. We then calculate the fractions of: - lost", "one column with the retention rate \"\"\" # determine what are the responses", "with the retention rate \"\"\" # determine what are the responses to the", "responses to the \"last used Kite\" / \"last used Python\" questions that indicate", "fix this, we look at the results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey", "counts for the following columns - [unactivated, activate, lost, dormant] - e.g. as", "are the responses to the \"last used Kite\" / \"last used Python\" questions", "from typing import Callable import datetime import pandas as pd def naive_retention_fn(df: pd.DataFrame)", "the \"true retention\" rate given a DataFrame of daily user counts by cohort", "+ (dormant_count * dormant_active_rate) + (lost_count * lost_active_rate) churned_users = (dormant_count * dormant_lost_rate)", "\"\"\" # determine what are the responses to the \"last used Kite\" /", "windows survey result, as returned by windows_survey.get_responses() :param active_days: the active-day definition (the", "rate given a DataFrame of daily user counts by cohort (e.g. as returned", "be in {14,30,90}\") # we only consider respondents who answered both of the", "{'14', '30', '90'} else: raise ValueError(\"active_days needs to be in {14,30,90}\") # we", "(df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate) return active / (active + churned)", "+ churned_users) :param histories: user history DataFrame, as returned by load_user_histories() :param users:", "user's survey responses at face value. We then calculate the fractions of: -", "& dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active", "dormant and lost users may be incorrect (due to the fact that it", "for the following columns - [unactivated, activate, lost, dormant] - e.g. as returned", "<active_days> (dormant_active_rate) We then apply corrections to the retention rate by redistributing our", "We then apply corrections to the retention rate by redistributing our lost and", "achieve this, we begin with the assumption that when looking at just the", "DataFrame, as returned by get_user_totals() :param win_survey: windows survey result, as returned by", "!= '') & (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)]", "< resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active)", "(lost_count * lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate", "\"last used Kite\"/ \"last used Python\" questions resps = win_survey[(win_survey.last_used_kite != '') &", "(lost_active_rate) - dormant (categorized by us) survey respondents who claim to have used", "elif active_days == 30: active_choices = {'14', '30'} elif active_days == 90: active_choices", "just the numbers from kite_status events, our categorization of dormant and lost users", "both Kite and Python within the past <active_days> (lost_active_rate) - dormant (categorized by", "window if active_days == 14: active_choices = {'14'} elif active_days == 30: active_choices", "used Python\" questions that indicate the user # is still using Kite/Python within", "get_user_totals() :param win_survey: windows survey result, as returned by windows_survey.get_responses() :param active_days: the", "import pandas as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention", "win_survey: windows survey result, as returned by windows_survey.get_responses() :param active_days: the active-day definition", "lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost = lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate", "may be incorrect (due to the fact that it may count ineligible users,", ":param df: a DataFrame containing user counts for the following columns - [unactivated,", "daily user counts by cohort (e.g. as returned by counts_for_daily_cohort()) For the motivation", "may count ineligible users, or issues with collecting metrics). To fix this, we", "the results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about", "we look at the results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey", "at least if we take that user's survey responses at face value. We", "(categorized by us) survey respondents who claim to have used Python but not", "dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) &", "df.dormant) def true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a", "def true_retention_fn( win_survey: pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function", "holds for every measured cohort. active_users = active_count + (dormant_count * dormant_active_rate) +", "with the same index as df, containing the calculated retention rate for each", "<active_days> (lost_lost_rate) - lost (categorized by us) survey respondents who claim to have", "metrics). To fix this, we look at the results of the Windows user", "/ len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps)", "dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate", "dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active", "used both Kite and Python within the past <active_days> (lost_active_rate) - dormant (categorized", "results of the Windows user survey: https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey This survey includes questions about the", "as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\" Calculates naive retention rate based", ":return: a function that operates on a DataFrame containing user counts for the", "== 90: active_choices = {'14', '30', '90'} else: raise ValueError(\"active_days needs to be", "lost or dormant, at least if we take that user's survey responses at", "calculate the \"true retention\" rate given a DataFrame of daily user counts by", "this, we begin with the assumption that when looking at just the numbers", "# is still using Kite/Python within the desired window if active_days == 14:", "len(dormant_resps) def retention_fn(df: pd.DataFrame) -> pd.Series: active = df.active + (df.dormant * dormant_active_rate)", "the gist of it is that we want to find out the rate", "by counts_for_daily_cohort() :return: a Series, with the same index as df, containing the", "raise ValueError(\"active_days needs to be in {14,30,90}\") # we only consider respondents who", "as returned by load_user_histories() :param users: users DataFrame, as returned by get_user_totals() :param", "(dormant_count * dormant_active_rate) + (lost_count * lost_active_rate) churned_users = (dormant_count * dormant_lost_rate) +", "active_choices = {'14'} elif active_days == 30: active_choices = {'14', '30'} elif active_days", "then apply corrections to the retention rate by redistributing our lost and dormant", "(dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate = active_users / (active_users +", "and the last time a user coded using Kite. From these we can", "containing just one column with the retention rate \"\"\" # determine what are", "the assumption that this rate holds for every measured cohort. active_users = active_count", "redistributing our lost and dormant users according to these calculated rates, using the", "the calculated retention rate for each row \"\"\" return df.active / (df.active +", "survey respondents who claim to have used both Kite and Python within the", "within the past <active_days> (lost_lost_rate) - lost (categorized by us) survey respondents who", "import Callable import datetime import pandas as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series:", "collecting metrics). To fix this, we look at the results of the Windows", "dormant_resps[ ~dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_lost_rate = len(dormant_lost) / len(dormant_resps) def retention_fn(df: pd.DataFrame) ->", "us) survey respondents who claim to have used Python but not Kite within", "pd.DataFrame, active_days: int) -> Callable[[pd.DataFrame], pd.Series]: \"\"\" Returns a function that can calculate", "lost users may be incorrect (due to the fact that it may count", "datetime.timedelta(days=active_days)] lost_active = lost_resps[ lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_active_rate = len(lost_active) / len(lost_resps) lost_lost", "us) survey respondents who claim to have used both Kite and Python within", ":param win_survey: windows survey result, as returned by windows_survey.get_responses() :param active_days: the active-day", "a user coded using Kite. From these we can determine whether a user", "e.g. as returned by counts_for_daily_cohort() :return: a Series, with the same index as", "following columns - [unactivated, activate, lost, dormant] - e.g. as returned by counts_for_daily_cohort()", "time a user coded in Python and the last time a user coded", "'') & (win_survey.last_used_py != '')] lost_resps = resps[resps.last_day < resps.started - datetime.timedelta(days=active_days)] lost_active", "datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)]", "if we take that user's survey responses at face value. We then calculate", "with the assumption that when looking at just the numbers from kite_status events,", "'90'} else: raise ValueError(\"active_days needs to be in {14,30,90}\") # we only consider", "function that operates on a DataFrame containing user counts for the following columns", "using Kite/Python within the desired window if active_days == 14: active_choices = {'14'}", "the following columns - [unactivated, activate, lost, dormant] and returns a series containing", "dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate = active_users / (active_users + churned_users) :param", "user coded using Kite. From these we can determine whether a user is", "it is that we want to find out the rate at which eligible", "Python\" questions resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')] lost_resps =", "users DataFrame, as returned by get_user_totals() :param win_survey: windows survey result, as returned", "[unactivated, activate, lost, dormant] - e.g. as returned by counts_for_daily_cohort() :return: a Series,", "is truly lost or dormant, at least if we take that user's survey", "a function that can calculate the \"true retention\" rate given a DataFrame of", "\"\"\" return df.active / (df.active + df.lost + df.dormant) def true_retention_fn( win_survey: pd.DataFrame,", "based entirely on the kite_status data :param df: a DataFrame containing user counts", "returns a series containing just one column with the retention rate \"\"\" #", "to the fact that it may count ineligible users, or issues with collecting", "= dormant_resps[ dormant_resps.last_used_kite.isin(active_choices) & dormant_resps.last_used_py.isin(active_choices)] dormant_active_rate = len(dormant_active) / len(dormant_resps) dormant_lost = dormant_resps[", "lost_resps[ ~lost_resps.last_used_kite.isin(active_choices) & lost_resps.last_used_py.isin(active_choices)] lost_lost_rate = len(lost_lost) / len(lost_resps) dormant_resps = resps[(resps.last_day >=", "determine whether a user is truly lost or dormant, at least if we", "Callable import datetime import pandas as pd def naive_retention_fn(df: pd.DataFrame) -> pd.Series: \"\"\"", "to these calculated rates, using the assumption that this rate holds for every", "the past <active_days> (lost_active_rate) - dormant (categorized by us) survey respondents who claim", "used Python\" questions resps = win_survey[(win_survey.last_used_kite != '') & (win_survey.last_used_py != '')] lost_resps", "+ (df.lost * lost_active_rate) churned = (df.dormant * dormant_lost_rate) + (df.lost * lost_lost_rate)", "that this rate holds for every measured cohort. active_users = active_count + (dormant_count", "use a Kite-supported editor) retain. To achieve this, we begin with the assumption", "active_users = active_count + (dormant_count * dormant_active_rate) + (lost_count * lost_active_rate) churned_users =", "our lost and dormant users according to these calculated rates, using the assumption", "by us) survey respondents who claim to have used Python but not Kite", "numbers from kite_status events, our categorization of dormant and lost users may be", "is still using Kite/Python within the desired window if active_days == 14: active_choices", "DataFrame, as returned by load_user_histories() :param users: users DataFrame, as returned by get_user_totals()", "(the \"n\" in \"n-day active\") :return: a function that operates on a DataFrame", "resps.started - datetime.timedelta(days=active_days)) & (resps.last_py_event < resps.started - datetime.timedelta(days=active_days))] dormant_active = dormant_resps[ dormant_resps.last_used_kite.isin(active_choices)", "we want to find out the rate at which eligible users (i.e. those", "last time a user coded in Python and the last time a user", "= (dormant_count * dormant_lost_rate) + (lost_count * lost_lost_rate) true_retention_rate = active_users / (active_users", "returned by counts_for_daily_cohort()) For the motivation behind finding the true retention rate, see:", "calculated rates, using the assumption that this rate holds for every measured cohort.", "dormant, at least if we take that user's survey responses at face value.", "given a DataFrame of daily user counts by cohort (e.g. as returned by" ]
[ "panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except", "with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_js not in text assert", "\"\"\"The purpose of this module is to test the TemporaryResources context manager The", "= pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\"", "js_file}): text = pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with", "disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [ file for file", "\"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text) def", "assert extension in text assert pre_raw_css not in text assert pre_css_file not in", "with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files():", "pre_extension not in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {\"somejs\": pre_js}", "templates, like for example a light template, a dark template, a bootstrap template,", "your templates you will include the same css and js files in all", "for example a light template, a dark template, a bootstrap template, a material", "template, a material template, a template with Plotly Plots, a template without Plotly", "not in text assert extension in text assert pre_raw_css not in text assert", "text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def test_complex_use_case(): # Given pre_raw_css", "clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [] def", "# When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files with", "= \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file in text assert", "files in all templates. This is problematic if you want different templates, like", "bootstrap template, a material template, a template with Plotly Plots, a template without", "template, a dark template, a bootstrap template, a material template, a template with", "pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_css_file", "template without Plotly plots etc. \"\"\" import panel as pn import pytest from", "= pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text assert \"bokeh-widgets\" in text assert", "in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\"", "configuration `pn.config` for your templates you will include the same css and js", "global configuration `pn.config` for your templates you will include the same css and", "def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files", "backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert \"bokeh-\"", "\"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources(): text", "assert pre_extension not in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {\"somejs\":", "in text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file", "When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert", "\"bokeh-widgets\" in text assert \"bokeh-tables\" in text assert \".panel-widget-box\" not in text assert", "assert pre_js not in text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension():", "in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text", "pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text =", "# Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources():", "assert \"bokeh-tables\" in text assert \".panel-widget-box\" not in text assert extension in text", "_contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text", "backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file)", "_contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup =", "assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]):", "you use the global configuration `pn.config` for your templates you will include the", "\"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files", "pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False):", "= pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_js not in", ") def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css)", "= pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\"", "to test the TemporaryResources context manager The purpose of the TemporaryResources context manager", "pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text assert \"bokeh-widgets\" in text assert \"bokeh-tables\"", "in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]):", "When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert", "= pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert \"bokeh-\" in", "pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files with", "TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def test_complex_use_case(): # Given", "is to test the TemporaryResources context manager The purpose of the TemporaryResources context", "black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\"", "css and js files in all templates. This is problematic if you want", "text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {\"somejs\": pre_js} assert pn.config.css_files ==", "you will include the same css and js files in all templates. This", "will include the same css and js files in all templates. This is", "\"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\" # When pn.extension(pre_extension)", "with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text) def", "creating a custom Template. If you use the global configuration `pn.config` for your", "text = pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css =", "assert pre_raw_css not in text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files():", "Given pre_raw_css = \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension", "templates you will include the same css and js files in all templates.", "and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background: black;\" #", "from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config", "pre_css_file not in text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): #", "raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in", "test_includes_template_raw_css(): raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css", "with Plotly Plots, a template without Plotly plots etc. \"\"\" import panel as", "assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\"", "backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" # When pn.extension(pre_extension)", "= [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and \"bokeh-widgets\" in text", "pre_extension = \"plotly\" extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files =", "text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text =", "Template. If you use the global configuration `pn.config` for your templates you will", "extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background: black;\" with", "pn import pytest from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def", "TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_raw_css not in text assert pn.config.raw_css", "pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\" #", "Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text", "\"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in text assert", "backup = pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_js not", "temporary, specific configuration of resources when creating a custom Template. If you use", "text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension =", "use the global configuration `pn.config` for your templates you will include the same", "as pn import pytest from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True)", "in text assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in text assert \".panel-widget-box\" not", "= \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text", "\"\"\"Reset pn.config except for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files", "text = pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False):", "When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension},", "extension in text assert pre_raw_css not in text assert pre_css_file not in text", "not in text assert pre_extension not in text assert pn.config.raw_css == [pre_raw_css] assert", "pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def test_complex_use_case(): # Given pre_raw_css = \"body", "pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and \"bokeh-widgets\" in", "# pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [ file", "pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css)", "\"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension", "test the TemporaryResources context manager The purpose of the TemporaryResources context manager is", "= {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and", "manager is to enable using temporary, specific configuration of resources when creating a", "Then assert \"bokeh-\" in text assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in text", "= \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file)", "TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel", "pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_raw_css not in text", "css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}):", "_contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\":", "pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_js not in text", "# Then assert \"bokeh-\" in text assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in", "{\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert", "text assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in text assert \".panel-widget-box\" not in", "text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not", "pn.io.resources.Resources().render() # Then assert pre_raw_css not in text assert pn.config.raw_css == backup assert", "assert pre_css_file not in text assert pre_js not in text assert pre_extension not", "problematic if you want different templates, like for example a light template, a", "css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in text assert", "{background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render()", "with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files():", "pre_raw_css not in text assert pre_css_file not in text assert pre_js not in", "with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_raw_css not in text assert", "assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text =", "def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text", "# Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension =", "and \"bokeh-widgets\" in text and \"bokeh-tables\" in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css():", "and js files in all templates. This is problematic if you want different", "black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() #", "in text assert pre_css_file not in text assert pre_js not in text assert", "TemporaryResources context manager The purpose of the TemporaryResources context manager is to enable", "When pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render()", "text = pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text assert \"bokeh-widgets\" in text", "and \"bokeh-tables\" in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css =", "css\"\"\" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [", "clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css = []", "custom Template. If you use the global configuration `pn.config` for your templates you", "pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" #", "want different templates, like for example a light template, a dark template, a", "templates. This is problematic if you want different templates, like for example a", "file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css =", "\"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files", "pre_js not in text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): #", "assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render()", "not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text", "pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [ file for", "{background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text)", "pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with", "include the same css and js files in all templates. This is problematic", "\"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text):", "def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js}", "same css and js files in all templates. This is problematic if you", "backup = pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_raw_css not", "Given pre_extension = \"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() #", "not in text def test_complex_use_case(): # Given pre_raw_css = \"body {background: black;\" pre_css_file", "text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text", "def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in", "pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" #", "pn.config.js_files = {} pn.config.css_files = [ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file)", "the TemporaryResources context manager is to enable using temporary, specific configuration of resources", "pn.config except for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files =", "def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = []", "not in text assert pre_css_file not in text assert pre_js not in text", "extension = \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in text assert", "in text and \"bokeh-widgets\" in text and \"bokeh-tables\" in text and \".panel-widget-box\" )", "Plots, a template without Plotly plots etc. \"\"\" import panel as pn import", "in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text =", "assert pre_css_file not in text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files():", "= \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\" # When", "{} pn.config.css_files = [ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture()", "= \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\"", "= {} pn.config.css_files = [ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ]", "pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return (", "= pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body", "\".panel-widget-box\" not in text def test_complex_use_case(): # Given pre_raw_css = \"body {background: black;\"", "= [] pn.config.js_files = {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\"", "Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\"", "you want different templates, like for example a light template, a dark template,", "# When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then", "assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" # When pn.extension(pre_extension) with", "assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\"", "pn.config.css_files = [ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def", "assert extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background: black;\"", "\"bokeh-\" in text assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in text assert \".panel-widget-box\"", "= pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_css_file not in", "_contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render()", "\"bokeh-tables\" in text assert \".panel-widget-box\" not in text assert extension in text assert", "# pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\"", "return ( \"bokeh-\" in text and \"bokeh-widgets\" in text and \"bokeh-tables\" in text", "def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css =", "pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files", "with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def test_complex_use_case(): #", "all templates. This is problematic if you want different templates, like for example", "enable using temporary, specific configuration of resources when creating a custom Template. If", "text assert pre_js not in text assert pre_extension not in text assert pn.config.raw_css", "a bootstrap template, a material template, a template with Plotly Plots, a template", "# Then assert pre_js not in text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text)", "etc. \"\"\" import panel as pn import pytest from panel_components.resources import TemporaryResources #", "# When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension not", "example a light template, a dark template, a bootstrap template, a material template,", "disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\" # pylint:", "configuration of resources when creating a custom Template. If you use the global", "template with Plotly Plots, a template without Plotly plots etc. \"\"\" import panel", "\"bokeh-\" in text and \"bokeh-widgets\" in text and \"bokeh-tables\" in text and \".panel-widget-box\"", "# Then assert pre_css_file not in text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text)", "pre_raw_css = \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension =", "= {\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then", "= pn.io.resources.Resources().render() # Then assert pre_raw_css not in text assert pn.config.raw_css == backup", "with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_css_file not in text assert", "# Then assert pre_raw_css not in text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text)", "in text def test_complex_use_case(): # Given pre_raw_css = \"body {background: black;\" pre_css_file =", "TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text assert \"bokeh-widgets\"", "pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() #", "def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup", "panel as pn import pytest from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\",", "text assert \"bokeh-tables\" in text assert \".panel-widget-box\" not in text assert extension in", "{} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and \"bokeh-widgets\"", "this module is to test the TemporaryResources context manager The purpose of the", "without Plotly plots etc. \"\"\" import panel as pn import pytest from panel_components.resources", "def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def", "specific configuration of resources when creating a custom Template. If you use the", "def test_includes_template_raw_css(): raw_css = \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert", "_contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file", "in text assert extension in text assert pre_raw_css not in text assert pre_css_file", "pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}):", "pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_css_file not in text", "test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def test_complex_use_case():", "\"\"\" import panel as pn import pytest from panel_components.resources import TemporaryResources # pylint:", "Then assert pre_raw_css not in text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def", "text = pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file =", "TemporaryResources context manager is to enable using temporary, specific configuration of resources when", "# When pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources(): text =", "# Given pre_raw_css = \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css", "pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text", "text = pn.io.resources.Resources().render() # Then assert pre_raw_css not in text assert pn.config.raw_css ==", "def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file", "if you want different templates, like for example a light template, a dark", "@pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files =", "assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert", "def test_complex_use_case(): # Given pre_raw_css = \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js", "in text assert pre_extension not in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files", "The purpose of the TemporaryResources context manager is to enable using temporary, specific", "not in text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given", "TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {}", "= pn.io.resources.Resources().render() # Then assert pre_css_file not in text assert pn.config.css_files == backup", "text = pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file =", "pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css = \"body {background:", "is to enable using temporary, specific configuration of resources when creating a custom", "[ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset", "not in text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given", "pn.config.js_files = {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text", "TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_js not in text assert pn.config.js_files", "test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with", "pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension not in text", "extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files", "pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text =", "in text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension", "= pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text", "\"bokeh-widgets\" in text and \"bokeh-tables\" in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): #", "assert css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\":", "text = pn.io.resources.Resources().render() # Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def", "_contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and \"bokeh-widgets\" in text and \"bokeh-tables\" in", "in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {\"somejs\": pre_js} assert pn.config.css_files", "test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js} backup", "assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files =", "template, a bootstrap template, a material template, a template with Plotly Plots, a", "of the TemporaryResources context manager is to enable using temporary, specific configuration of", "assert pre_js not in text assert pre_extension not in text assert pn.config.raw_css ==", "# Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js} backup =", "= \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text)", "module is to test the TemporaryResources context manager The purpose of the TemporaryResources", "text assert extension in text assert pre_raw_css not in text assert pre_css_file not", "{\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then", "when creating a custom Template. If you use the global configuration `pn.config` for", "test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text =", "a custom Template. If you use the global configuration `pn.config` for your templates", "pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return", "= {\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() #", "= pn.io.resources.Resources().render() # Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension():", "assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\"", "_contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" # When pn.extension(pre_extension) with TemporaryResources():", "Then assert pre_css_file not in text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def", "in all templates. This is problematic if you want different templates, like for", "= [ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config():", "in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = []", "If you use the global configuration `pn.config` for your templates you will include", "Plotly Plots, a template without Plotly plots etc. \"\"\" import panel as pn", "test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in text", "assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert \".panel-widget-box\" not in", "raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text", "TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file", "= \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js} backup_css_files =", "for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css", "the global configuration `pn.config` for your templates you will include the same css", "TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text)", "of this module is to test the TemporaryResources context manager The purpose of", "{background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension =", "in text and \"bokeh-tables\" in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given", "in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background:", "assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert", "= pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_raw_css not in", "test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup =", "a template with Plotly Plots, a template without Plotly plots etc. \"\"\" import", "( \"bokeh-\" in text and \"bokeh-widgets\" in text and \"bokeh-tables\" in text and", "= \"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert", "] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files", "panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files =", "\"plotly\" extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\": pre_js}", "text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js =", "pytest from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset", "pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_raw_css", "assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {\"somejs\": pre_js} assert pn.config.css_files == backup_css_files", "pre_css_file not in text assert pre_js not in text assert pre_extension not in", "= \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render()", "purpose of this module is to test the TemporaryResources context manager The purpose", "for your templates you will include the same css and js files in", "text = pn.io.resources.Resources().render() # Then assert pre_js not in text assert pn.config.js_files ==", "a material template, a template with Plotly Plots, a template without Plotly plots", "test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file in", "not in text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given", "= \"body {background: black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in text", "[] pn.config.js_files = {} pn.config.css_files = [ file for file in pn.config.css_files if", "Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files", "autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css", "assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup", "_contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension", "\"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text) def", "pre_extension = \"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then", "Then assert pre_js not in text assert pn.config.js_files == backup assert _contains_bokeh_and_panel_resources(text) def", "This is problematic if you want different templates, like for example a light", "include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text assert \"bokeh-widgets\" in", "text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render()", "light template, a dark template, a bootstrap template, a material template, a template", "== backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_extension(): # Given pre_extension = \"plotly\" # When", "not in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {\"somejs\": pre_js} assert", "a light template, a dark template, a bootstrap template, a material template, a", "js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file in text", "pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text =", "def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and \"bokeh-widgets\" in text and \"bokeh-tables\"", "of resources when creating a custom Template. If you use the global configuration", "assert \".panel-widget-box\" not in text assert extension in text assert pre_raw_css not in", "the same css and js files in all templates. This is problematic if", "text and \"bokeh-tables\" in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css", "text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file =", "text assert pre_raw_css not in text assert pre_css_file not in text assert pre_js", "test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render() assert css_file in text", "== backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): # Given pre_css_file = \"https://somedomain.com/test.css\" # When", "pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with", "# Given pre_extension = \"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render()", "black;\" with TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def", "TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css(): raw_css", "pn.io.resources.Resources().render() # Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension", "template, a template with Plotly Plots, a template without Plotly plots etc. \"\"\"", "using temporary, specific configuration of resources when creating a custom Template. If you", "pre_raw_css not in text assert pn.config.raw_css == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_css_files(): #", "text assert pre_extension not in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files ==", "to enable using temporary, specific configuration of resources when creating a custom Template.", "# When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text = pn.io.resources.Resources().render() # Then", "\"plotly\" # When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension", "js files in all templates. This is problematic if you want different templates,", "with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text assert", "TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_css_file not in text assert pn.config.css_files", "import pytest from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css():", "purpose of the TemporaryResources context manager is to enable using temporary, specific configuration", "like for example a light template, a dark template, a bootstrap template, a", "context manager is to enable using temporary, specific configuration of resources when creating", "When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension not in", "plots etc. \"\"\" import panel as pn import pytest from panel_components.resources import TemporaryResources", "material template, a template with Plotly Plots, a template without Plotly plots etc.", "text assert \".panel-widget-box\" not in text assert extension in text assert pre_raw_css not", "pn.config.js_files = {\"somejs\": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render()", "pre_raw_css = \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources():", "not in text assert pre_js not in text assert pre_extension not in text", "_contains_bokeh_and_panel_resources(text) def test_includes_template_js_files(): js_file = \"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert", "js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render() assert", "# Given pre_raw_css = \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\"", "pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert \"bokeh-\" in text", "in text assert pre_raw_css not in text assert pre_css_file not in text assert", "text def test_complex_use_case(): # Given pre_raw_css = \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\"", "\".panel-widget-box\" not in text assert extension in text assert pre_raw_css not in text", "`pn.config` for your templates you will include the same css and js files", "pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert", "@pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for panel css\"\"\" # pylint: disable=protected-access", "assert js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css(): with TemporaryResources(include_panel_css=False): text = pn.io.resources.Resources().render()", "manager The purpose of the TemporaryResources context manager is to enable using temporary,", "in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text =", "assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_extension(): extension = \"katex\" with", "pre_css_file = \"https://somedomain.com/test.css\" pre_js = \"http://some/domain.com/test.js\" pre_extension = \"plotly\" extension = \"katex\" #", "text and \"bokeh-widgets\" in text and \"bokeh-tables\" in text and \".panel-widget-box\" ) def", "in text assert \".panel-widget-box\" not in text assert extension in text assert pre_raw_css", "[] pn.config.js_files = {} pn.config.css_files = [] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in", "def test_includes_template_extension(): extension = \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in", "assert \".panel-widget-box\" not in text def test_complex_use_case(): # Given pre_raw_css = \"body {background:", "= \"plotly\" extension = \"katex\" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {\"somejs\":", "context manager The purpose of the TemporaryResources context manager is to enable using", "assert \"bokeh-\" in text assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in text assert", "in text assert pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js", "\"https://somedomain.com/test.css\" # When pn.config.css_files.append(pre_css_file) backup = pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() #", "TemporaryResources(raw_css=[raw_css]): text = pn.io.resources.Resources().render() assert raw_css in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file", "assert \"bokeh-widgets\" in text assert \"bokeh-tables\" in text assert \".panel-widget-box\" not in text", "for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files", "a dark template, a bootstrap template, a material template, a template with Plotly", "= [] pn.config.js_files = {} pn.config.css_files = [ file for file in pn.config.css_files", "pre_js} backup = pn.config.js_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_js", "pn.io.resources.Resources().render() # Then assert pre_css_file not in text assert pn.config.css_files == backup assert", "backup = pn.config.css_files with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_css_file not", "dark template, a bootstrap template, a material template, a template with Plotly Plots,", "\"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with TemporaryResources(): text =", "\".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background: black;\" # When", "\"http://some/domain.com/test.js\" with TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text)", "backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" # When pn.config.js_files", "TemporaryResources(js_files={\"somejs\": js_file}): text = pn.io.resources.Resources().render() assert js_file in text assert _contains_bokeh_and_panel_resources(text) def test_can_exclude_panel_css():", "pn.config.css_files == backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" #", "text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body {background: black;\"", "[] def _contains_bokeh_and_panel_resources(text): return ( \"bokeh-\" in text and \"bokeh-widgets\" in text and", "is problematic if you want different templates, like for example a light template,", "pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [ file for file in", "Given pre_raw_css = \"body {background: black;\" # When pn.config.raw_css.append(pre_raw_css) backup = pn.config.raw_css with", "= \"katex\" with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text)", "text assert pre_css_file not in text assert pre_js not in text assert pre_extension", "except for panel css\"\"\" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {}", "import TemporaryResources # pylint: disable=missing-function-docstring @pytest.fixture(scope=\"function\", autouse=True) def clear_config_except_panel_css(): \"\"\"Reset pn.config except for", "= \"http://some/domain.com/test.js\" # When pn.config.js_files = {\"somejs\": pre_js} backup = pn.config.js_files with TemporaryResources():", "Plotly plots etc. \"\"\" import panel as pn import pytest from panel_components.resources import", "= pn.io.resources.Resources().render() assert \".panel-widget-box\" not in text def test_complex_use_case(): # Given pre_raw_css =", "test_complex_use_case(): # Given pre_raw_css = \"body {background: black;\" pre_css_file = \"https://somedomain.com/test.css\" pre_js =", "in text assert \"bokeh-tables\" in text assert \".panel-widget-box\" not in text assert extension", "with TemporaryResources(extensions={extension}): text = pn.io.resources.Resources().render() assert extension in text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_raw_css():", "pn.io.resources.Resources().render() # Then assert pre_js not in text assert pn.config.js_files == backup assert", "with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension not in text assert", "text assert _contains_bokeh_and_panel_resources(text) def test_includes_template_css_files(): css_file = \"https://somedomain.com/test.css\" with TemporaryResources(css_files=[css_file]): text = pn.io.resources.Resources().render()", "assert pre_raw_css not in text assert pre_css_file not in text assert pre_js not", "= pn.io.resources.Resources().render() # Then assert pre_js not in text assert pn.config.js_files == backup", "if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\" pn.config.raw_css = [] pn.config.js_files =", "\"bokeh-tables\" in text and \".panel-widget-box\" ) def test_does_not_include_pn_config_raw_css(): # Given pre_raw_css = \"body", "text = pn.io.resources.Resources().render() # Then assert pre_css_file not in text assert pn.config.css_files ==", "file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ] @pytest.fixture() def clear_config(): \"\"\"Reset pn.config\"\"\"", "the TemporaryResources context manager The purpose of the TemporaryResources context manager is to", "in text assert pre_js not in text assert pre_extension not in text assert", "import panel as pn import pytest from panel_components.resources import TemporaryResources # pylint: disable=missing-function-docstring", "resources when creating a custom Template. If you use the global configuration `pn.config`", "pre_js not in text assert pre_extension not in text assert pn.config.raw_css == [pre_raw_css]", "a template without Plotly plots etc. \"\"\" import panel as pn import pytest", "== backup assert _contains_bokeh_and_panel_resources(text) def test_does_not_include_pn_config_js_files(): # Given pre_js = \"http://some/domain.com/test.js\" # When", "different templates, like for example a light template, a dark template, a bootstrap" ]
[ "= validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry():", "validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\",", "\"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket", "assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert (", "validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") ==", "freeldep.modules.create import validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create", "validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\")) ==", "def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with", "pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0]", "<reponame>MatthieuBlais/freeldep import pytest from freeldep.modules.create import validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create", "assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\")) == 2 assert", "\"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\")", "validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\")", "from freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") ==", "registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert", "assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\")", "assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\")", "6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\"", "== \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert", "validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert", "= validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\"))", "( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\",", "freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") ==", "== \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert", "pytest from freeldep.modules.create import validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name", "validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\",", "None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\",", "def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket =", "pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError):", "== \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\")", "test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\",", ") with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\"", "with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert", "assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None)", "assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) ==", "import validate_name from freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert", "bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def", "== \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\"", "pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1])", "from freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", "validate_name from freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert (", "\"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\")", "validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\"", "def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\")) == 2 assert len(validate_emails(\"<EMAIL>,test2\")) ==", "validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert", "from freeldep.modules.create import validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name from", "\"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def", "freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry def test_validate_name():", "validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] ==", "test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError):", "bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") ==", "def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\",", "\"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry", "bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert", "validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) ==", "registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\")) == 2 assert len(validate_emails(\"<EMAIL>,test2\"))", "== \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\")", "import pytest from freeldep.modules.create import validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create import", "assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket():", "with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert", "( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert", "\"testbucket\" with pytest.raises(ValueError): validate_bucket(\"test\", \"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\")", "== 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\",", "with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") == \"testbucket\" with", "freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\"", "from freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry def", "test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\")) == 2 assert len(validate_emails(\"<EMAIL>,test2\")) == 1", "\"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry =", "test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", )", ") == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None)", "None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\" assert len(validate_emails(\"<EMAIL>,<EMAIL>\")) == 2", ") with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails():", "\"testbucket@\") bucket = validate_bucket(\"test\", None) assert bucket.startswith(\"test\") assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6", "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def test_validate_bucket(): assert validate_bucket(\"test\", \"testbucket\") ==", "\"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError): validate_bucket(\"test\", \"testregistry@\") registry = validate_registry(\"test\",", "\"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" ) with pytest.raises(ValueError): validate_name(\"sdfsdfd223!#fsdf\") == \"sdfsdfdfsdf\" def", "assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with pytest.raises(ValueError):", "validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\")", "import validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create import", "validate_bucket from freeldep.modules.create import validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry", "\"testregistry\") == \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\"", "assert bucket.startswith(\"test-deployer-artifact-bucket-\") assert len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\"", "\"testregistry@\") registry = validate_registry(\"test\", None) assert registry.startswith(\"test\") def test_validate_emails(): assert validate_emails(\"<EMAIL>\")[0] == \"<EMAIL>\"", "len(bucket.split(\"-\")[-1]) == 6 def test_validate_registry(): assert validate_registry(\"test\", \"testregistry\") == \"testregistry\" assert ( validate_registry(", "== \"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" )", "import validate_emails from freeldep.modules.create import validate_name from freeldep.modules.create import validate_registry def test_validate_name(): assert", "validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", "\"testregistry\" assert ( validate_registry( \"test\", \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssssssss\", ) == \"testregistrysssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\" \"sssssssssssssssssssss\" ) with", "import validate_registry def test_validate_name(): assert validate_name(\"sdfsdfdfsdf\") == \"sdfsdfdfsdf\" assert ( validate_name(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") == \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"" ]
[ "object. This function should use the NAPALM _get_checkpoint_file() method to retrieve a checkpoint", "is done using 'optional_args' in NAPALM so you should have the following key-value", "device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" *", "write it to the local file system. 4c. Manually copy the saved checkpoint", "device. It should then write this checkpoint out to a file. Recall that", "so you should have the following key-value pair defined: \"optional_args\": {\"port\": 8443} 4b.", "* 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after discarding the staged candidate:", "print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before commiting: \") print(\"#\" * 50) print(device_conn.compare_config())", "operations. Using this new function, retrieve a checkpoint from nxos1 and write it", "file. Ensure that you include the necessary information to set the NX-API port", "requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos napalm", "complete configuration replace operation (using the checkpoint file that you just retrieved and", "should take one argument, the NAPALM connection object. This function should use the", "a new file and add an additional loopback interface to the configuration. 4d.", "set the NX-API port to 8443. This is done using 'optional_args' in NAPALM", "the configuration to see your pending changes. After the compare_config is complete, then", "connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50)", "50) print(device_conn) # Creating the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint =", "my_functions.py file. This function should take one argument, the NAPALM connection object. This", "create_backup, create_checkpoint # Disable Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning", "file that you just retrieved and modified). Once your candidate configuration is staged", "_get_checkpoint_file() method to retrieve a checkpoint from the NX-OS device. It should then", "4a. Add nxos1 to your my_devices.py file. Ensure that you include the necessary", "local file system. 4c. Manually copy the saved checkpoint to a new file", "retrieved and modified). Once your candidate configuration is staged perform a compare_config (diff)", "your candidate configuration is staged perform a compare_config (diff) on the configuration to", "perform an additional compare_config (diff) to verify that you have no pending configuration", "on the configuration to see your pending changes. After the compare_config is complete,", "system. 4c. Manually copy the saved checkpoint to a new file and add", "Disable Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\":", "additional compare_config (diff) to verify that you have no pending configuration changes. Do", "of this exercise. \"\"\" import my_devices from pprint import pprint from napalm import", "Python script that stages a complete configuration replace operation (using the checkpoint file", "in NAPALM so you should have the following key-value pair defined: \"optional_args\": {\"port\":", "no pending configuration changes. Do not actually perform the commit_config as part of", "the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm", "This is done using 'optional_args' in NAPALM so you should have the following", "eliminate the pending changes. Next, perform an additional compare_config (diff) to verify that", "4c. Manually copy the saved checkpoint to a new file and add an", "Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs", "function, retrieve a checkpoint from nxos1 and write it to the local file", "NX-API port to 8443. This is done using 'optional_args' in NAPALM so you", "connection object. This function should use the NAPALM _get_checkpoint_file() method to retrieve a", "a complete configuration replace operation (using the checkpoint file that you just retrieved", "to verify that you have no pending configuration changes. Do not actually perform", "Using this new function, retrieve a checkpoint from nxos1 and write it to", "This function should use the NAPALM _get_checkpoint_file() method to retrieve a checkpoint from", "changes. After the compare_config is complete, then use the discard_config() method to eliminate", "* 50) print(device_conn) # Creating the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint", "Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the", "It should then write this checkpoint out to a file. Recall that the", "staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before commiting:", "# Creating the nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn", "just retrieved and modified). Once your candidate configuration is staged perform a compare_config", "# Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate", "a checkpoint from nxos1 and write it to the local file system. 4c.", "write this checkpoint out to a file. Recall that the NX-OS platform requires", "my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm", "napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions import", "get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate Warnings import", "from nxos1 and write it to the local file system. 4c. Manually copy", "the saved checkpoint to a new file and add an additional loopback interface", "checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm Config Replace", "create_checkpoint(device_conn, filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname}", "method to eliminate the pending changes. Next, perform an additional compare_config (diff) to", "new function named 'create_checkpoint'. Add this function into your my_functions.py file. This function", "perform a compare_config (diff) on the configuration to see your pending changes. After", "configuration to see your pending changes. After the compare_config is complete, then use", "napalm import get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate", "After the compare_config is complete, then use the discard_config() method to eliminate the", "import napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions", "device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before commiting: \")", "necessary information to set the NX-API port to 8443. This is done using", "NX-OS platform requires a 'checkpoint' file for configuration replace operations. Using this new", "the discard_config() method to eliminate the pending changes. Next, perform an additional compare_config", "should have the following key-value pair defined: \"optional_args\": {\"port\": 8443} 4b. Create a", "modified). Once your candidate configuration is staged perform a compare_config (diff) on the", "my_functions import napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate Warnings import requests from", "an additional loopback interface to the configuration. 4d. Create a Python script that", "import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos", "{nxos1_hostname} DIFFS candidate vs running before commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config()", "NX-OS device. It should then write this checkpoint out to a file. Recall", "print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after discarding", "compare_config is complete, then use the discard_config() method to eliminate the pending changes.", "loopback interface to the configuration. 4d. Create a Python script that stages a", "file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm Config Replace staging", "print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" * 50) print(device_conn) #", "part of this exercise. \"\"\" import my_devices from pprint import pprint from napalm", "NAPALM _get_checkpoint_file() method to retrieve a checkpoint from the NX-OS device. It should", "= nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection: \")", "filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS", "checkpoint out to a file. Recall that the NX-OS platform requires a 'checkpoint'", "Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running", "vs running after discarding the staged candidate: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.close()", "requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos napalm connection nxos1", "use the discard_config() method to eliminate the pending changes. Next, perform an additional", "configuration is staged perform a compare_config (diff) on the configuration to see your", "pprint from napalm import get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint # Disable", "have no pending configuration changes. Do not actually perform the commit_config as part", "to retrieve a checkpoint from the NX-OS device. It should then write this", "* 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running", "candidate vs running after discarding the staged candidate: \") print(\"#\" * 50) print(device_conn.compare_config())", "replace operation (using the checkpoint file that you just retrieved and modified). Once", "(diff) on the configuration to see your pending changes. After the compare_config is", "should use the NAPALM _get_checkpoint_file() method to retrieve a checkpoint from the NX-OS", "pprint import pprint from napalm import get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint", "replace operations. Using this new function, retrieve a checkpoint from nxos1 and write", "Recall that the NX-OS platform requires a 'checkpoint' file for configuration replace operations.", "checkpoint file that you just retrieved and modified). Once your candidate configuration is", "a 'checkpoint' file for configuration replace operations. Using this new function, retrieve a", "\") print(\"#\" * 50) print(device_conn) # Creating the nxos checkpoint file filename =", "the configuration. 4d. Create a Python script that stages a complete configuration replace", "Creating the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) #", "function should use the NAPALM _get_checkpoint_file() method to retrieve a checkpoint from the", "the NX-OS platform requires a 'checkpoint' file for configuration replace operations. Using this", "the necessary information to set the NX-API port to 8443. This is done", "a new function named 'create_checkpoint'. Add this function into your my_functions.py file. This", "platform requires a 'checkpoint' file for configuration replace operations. Using this new function,", "before commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname}", "you have no pending configuration changes. Do not actually perform the commit_config as", "the NAPALM connection object. This function should use the NAPALM _get_checkpoint_file() method to", "the NX-API port to 8443. This is done using 'optional_args' in NAPALM so", "not actually perform the commit_config as part of this exercise. \"\"\" import my_devices", "done using 'optional_args' in NAPALM so you should have the following key-value pair", "my_devices.py file. Ensure that you include the necessary information to set the NX-API", "to a file. Recall that the NX-OS platform requires a 'checkpoint' file for", "\"\"\" import my_devices from pprint import pprint from napalm import get_network_driver from my_functions", "operation (using the checkpoint file that you just retrieved and modified). Once your", "DIFFS candidate vs running after discarding the staged candidate: \") print(\"#\" * 50)", "to a new file and add an additional loopback interface to the configuration.", "(diff) to verify that you have no pending configuration changes. Do not actually", "from napalm import get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint # Disable Self-signed", "this function into your my_functions.py file. This function should take one argument, the", "if __name__==\"__main__\": # Creating the nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname =", "interface to the configuration. 4d. Create a Python script that stages a complete", "file for configuration replace operations. Using this new function, retrieve a checkpoint from", "= create_checkpoint(device_conn, filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing", "method to retrieve a checkpoint from the NX-OS device. It should then write", "verify that you have no pending configuration changes. Do not actually perform the", "checkpoint from the NX-OS device. It should then write this checkpoint out to", "print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" * 50) print(device_conn) # Creating the nxos", "and write it to the local file system. 4c. Manually copy the saved", "that the NX-OS platform requires a 'checkpoint' file for configuration replace operations. Using", "you should have the following key-value pair defined: \"optional_args\": {\"port\": 8443} 4b. Create", "that you have no pending configuration changes. Do not actually perform the commit_config", "this new function, retrieve a checkpoint from nxos1 and write it to the", "you just retrieved and modified). Once your candidate configuration is staged perform a", "is staged perform a compare_config (diff) on the configuration to see your pending", "the local file system. 4c. Manually copy the saved checkpoint to a new", "print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before commiting: \") print(\"#\"", "Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": #", "for configuration replace operations. Using this new function, retrieve a checkpoint from nxos1", "from pprint import pprint from napalm import get_network_driver from my_functions import napalm_conn, create_backup,", "into your my_functions.py file. This function should take one argument, the NAPALM connection", "include the necessary information to set the NX-API port to 8443. This is", "checkpoint = create_checkpoint(device_conn, filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50)", "your pending changes. After the compare_config is complete, then use the discard_config() method", "from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos napalm connection", "NAPALM connection object. This function should use the NAPALM _get_checkpoint_file() method to retrieve", "add an additional loopback interface to the configuration. 4d. Create a Python script", "the NX-OS device. It should then write this checkpoint out to a file.", "Do not actually perform the commit_config as part of this exercise. \"\"\" import", "stages a complete configuration replace operation (using the checkpoint file that you just", "# Disable Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if", "new file and add an additional loopback interface to the configuration. 4d. Create", "retrieve a checkpoint from the NX-OS device. It should then write this checkpoint", "information to set the NX-API port to 8443. This is done using 'optional_args'", "discard_config() method to eliminate the pending changes. Next, perform an additional compare_config (diff)", "nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing", "\"optional_args\": {\"port\": 8443} 4b. Create a new function named 'create_checkpoint'. Add this function", "Add nxos1 to your my_devices.py file. Ensure that you include the necessary information", "pending changes. Next, perform an additional compare_config (diff) to verify that you have", "checkpoint from nxos1 and write it to the local file system. 4c. Manually", "print(device_conn) # Creating the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn,", "Creating the nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn =", "print(\"#\" * 50) print(device_conn) # Creating the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\"", "Next, perform an additional compare_config (diff) to verify that you have no pending", "exercise. \"\"\" import my_devices from pprint import pprint from napalm import get_network_driver from", "f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" *", "the NAPALM _get_checkpoint_file() method to retrieve a checkpoint from the NX-OS device. It", "it to the local file system. 4c. Manually copy the saved checkpoint to", "nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection:", "actually perform the commit_config as part of this exercise. \"\"\" import my_devices from", "= f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\"", "candidate configuration is staged perform a compare_config (diff) on the configuration to see", "device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after discarding the", "import my_devices from pprint import pprint from napalm import get_network_driver from my_functions import", "function should take one argument, the NAPALM connection object. This function should use", "8443} 4b. Create a new function named 'create_checkpoint'. Add this function into your", "out to a file. Recall that the NX-OS platform requires a 'checkpoint' file", "'checkpoint' file for configuration replace operations. Using this new function, retrieve a checkpoint", "compare_config (diff) to verify that you have no pending configuration changes. Do not", "that stages a complete configuration replace operation (using the checkpoint file that you", "should then write this checkpoint out to a file. Recall that the NX-OS", "commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS", "Ensure that you include the necessary information to set the NX-API port to", "'create_checkpoint'. Add this function into your my_functions.py file. This function should take one", "This function should take one argument, the NAPALM connection object. This function should", "file system. 4c. Manually copy the saved checkpoint to a new file and", "the pending changes. Next, perform an additional compare_config (diff) to verify that you", "port to 8443. This is done using 'optional_args' in NAPALM so you should", "configuration. 4d. Create a Python script that stages a complete configuration replace operation", "and add an additional loopback interface to the configuration. 4d. Create a Python", "print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after discarding the staged", "to the configuration. 4d. Create a Python script that stages a complete configuration", "changes. Do not actually perform the commit_config as part of this exercise. \"\"\"", "using 'optional_args' in NAPALM so you should have the following key-value pair defined:", "Create a Python script that stages a complete configuration replace operation (using the", "__name__==\"__main__\": # Creating the nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname']", "pending changes. After the compare_config is complete, then use the discard_config() method to", "the following key-value pair defined: \"optional_args\": {\"port\": 8443} 4b. Create a new function", "copy the saved checkpoint to a new file and add an additional loopback", "function named 'create_checkpoint'. Add this function into your my_functions.py file. This function should", "Add this function into your my_functions.py file. This function should take one argument,", "new function, retrieve a checkpoint from nxos1 and write it to the local", "named 'create_checkpoint'. Add this function into your my_functions.py file. This function should take", "50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after", "additional loopback interface to the configuration. 4d. Create a Python script that stages", "your my_devices.py file. Ensure that you include the necessary information to set the", "\"\"\" 4a. Add nxos1 to your my_devices.py file. Ensure that you include the", "function into your my_functions.py file. This function should take one argument, the NAPALM", "this exercise. \"\"\" import my_devices from pprint import pprint from napalm import get_network_driver", "retrieve a checkpoint from nxos1 and write it to the local file system.", "take one argument, the NAPALM connection object. This function should use the NAPALM", "50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before commiting: \") print(\"#\" * 50)", "changes. Next, perform an additional compare_config (diff) to verify that you have no", "checkpoint to a new file and add an additional loopback interface to the", "nxos1 to your my_devices.py file. Ensure that you include the necessary information to", "8443. This is done using 'optional_args' in NAPALM so you should have the", "this checkpoint out to a file. Recall that the NX-OS platform requires a", "file. Recall that the NX-OS platform requires a 'checkpoint' file for configuration replace", "= napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" * 50)", "= my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname}", "your my_functions.py file. This function should take one argument, the NAPALM connection object.", "compare_config (diff) on the configuration to see your pending changes. After the compare_config", "import get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate Warnings", "then write this checkpoint out to a file. Recall that the NX-OS platform", "complete, then use the discard_config() method to eliminate the pending changes. Next, perform", "one argument, the NAPALM connection object. This function should use the NAPALM _get_checkpoint_file()", "4b. Create a new function named 'create_checkpoint'. Add this function into your my_functions.py", "from the NX-OS device. It should then write this checkpoint out to a", "the commit_config as part of this exercise. \"\"\" import my_devices from pprint import", "import pprint from napalm import get_network_driver from my_functions import napalm_conn, create_backup, create_checkpoint #", "nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\"", "to the local file system. 4c. Manually copy the saved checkpoint to a", "as part of this exercise. \"\"\" import my_devices from pprint import pprint from", "pending configuration changes. Do not actually perform the commit_config as part of this", "{nxos1_hostname} napalm connection: \") print(\"#\" * 50) print(device_conn) # Creating the nxos checkpoint", "see your pending changes. After the compare_config is complete, then use the discard_config()", "requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname", "Create a new function named 'create_checkpoint'. Add this function into your my_functions.py file.", "the nxos napalm connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1)", "argument, the NAPALM connection object. This function should use the NAPALM _get_checkpoint_file() method", "configuration replace operation (using the checkpoint file that you just retrieved and modified).", "a Python script that stages a complete configuration replace operation (using the checkpoint", "import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos napalm connection nxos1 =", "to your my_devices.py file. Ensure that you include the necessary information to set", "running before commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing", "an additional compare_config (diff) to verify that you have no pending configuration changes.", "use the NAPALM _get_checkpoint_file() method to retrieve a checkpoint from the NX-OS device.", "{\"port\": 8443} 4b. Create a new function named 'create_checkpoint'. Add this function into", "print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after discarding the staged candidate: \") print(\"#\"", "50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" * 50) print(device_conn) # Creating the", "to see your pending changes. After the compare_config is complete, then use the", "napalm connection nxos1 = my_devices.nxos1 nxos1_hostname = nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" *", "nxos1['hostname'] device_conn = napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\"", "have the following key-value pair defined: \"optional_args\": {\"port\": 8443} 4b. Create a new", "DIFFS candidate vs running before commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\"", "{nxos1_hostname} DIFFS candidate vs running after discarding the staged candidate: \") print(\"#\" *", "#!/usr/bin/env python \"\"\" 4a. Add nxos1 to your my_devices.py file. Ensure that you", "Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\") print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before", "\") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate", "Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating", "NAPALM so you should have the following key-value pair defined: \"optional_args\": {\"port\": 8443}", "napalm_conn(nxos1) print(\"#\" * 50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" * 50) print(device_conn)", "InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if __name__==\"__main__\": # Creating the nxos napalm connection nxos1 = my_devices.nxos1", "a checkpoint from the NX-OS device. It should then write this checkpoint out", "the checkpoint file that you just retrieved and modified). Once your candidate configuration", "the compare_config is complete, then use the discard_config() method to eliminate the pending", "Once your candidate configuration is staged perform a compare_config (diff) on the configuration", "requires a 'checkpoint' file for configuration replace operations. Using this new function, retrieve", "nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm Config", "* 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running before commiting: \") print(\"#\" *", "script that stages a complete configuration replace operation (using the checkpoint file that", "create_checkpoint # Disable Self-signed Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "to 8443. This is done using 'optional_args' in NAPALM so you should have", "nxos1 and write it to the local file system. 4c. Manually copy the", "to set the NX-API port to 8443. This is done using 'optional_args' in", "filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename) # Napalm Config Replace staging device_conn.load_replace_candidate(filename=f\"{nxos1_hostname}_config\")", "that you just retrieved and modified). Once your candidate configuration is staged perform", "* 50) print(f\"Printing {nxos1_hostname} napalm connection: \") print(\"#\" * 50) print(device_conn) # Creating", "napalm connection: \") print(\"#\" * 50) print(device_conn) # Creating the nxos checkpoint file", "commit_config as part of this exercise. \"\"\" import my_devices from pprint import pprint", "Manually copy the saved checkpoint to a new file and add an additional", "a compare_config (diff) on the configuration to see your pending changes. After the", "candidate vs running before commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" *", "my_devices from pprint import pprint from napalm import get_network_driver from my_functions import napalm_conn,", "connection: \") print(\"#\" * 50) print(device_conn) # Creating the nxos checkpoint file filename", "that you include the necessary information to set the NX-API port to 8443.", "pair defined: \"optional_args\": {\"port\": 8443} 4b. Create a new function named 'create_checkpoint'. Add", "and modified). Once your candidate configuration is staged perform a compare_config (diff) on", "staged perform a compare_config (diff) on the configuration to see your pending changes.", "key-value pair defined: \"optional_args\": {\"port\": 8443} 4b. Create a new function named 'create_checkpoint'.", "python \"\"\" 4a. Add nxos1 to your my_devices.py file. Ensure that you include", "following key-value pair defined: \"optional_args\": {\"port\": 8443} 4b. Create a new function named", "configuration changes. Do not actually perform the commit_config as part of this exercise.", "defined: \"optional_args\": {\"port\": 8443} 4b. Create a new function named 'create_checkpoint'. Add this", "50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs running after discarding the staged candidate: \")", "'optional_args' in NAPALM so you should have the following key-value pair defined: \"optional_args\":", "a file. Recall that the NX-OS platform requires a 'checkpoint' file for configuration", "# Creating the nxos checkpoint file filename = f\"{nxos1_hostname}_checkpoint\" checkpoint = create_checkpoint(device_conn, filename)", "saved checkpoint to a new file and add an additional loopback interface to", "to eliminate the pending changes. Next, perform an additional compare_config (diff) to verify", "perform the commit_config as part of this exercise. \"\"\" import my_devices from pprint", "configuration replace operations. Using this new function, retrieve a checkpoint from nxos1 and", "file and add an additional loopback interface to the configuration. 4d. Create a", "vs running before commiting: \") print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50)", "then use the discard_config() method to eliminate the pending changes. Next, perform an", "4d. Create a Python script that stages a complete configuration replace operation (using", "file. This function should take one argument, the NAPALM connection object. This function", "print(\"#\" * 50) print(device_conn.compare_config()) device_conn.discard_config() print(\"#\" * 50) print(f\"Printing {nxos1_hostname} DIFFS candidate vs", "(using the checkpoint file that you just retrieved and modified). Once your candidate", "you include the necessary information to set the NX-API port to 8443. This", "from my_functions import napalm_conn, create_backup, create_checkpoint # Disable Self-signed Certificate Warnings import requests", "is complete, then use the discard_config() method to eliminate the pending changes. Next," ]
[ "= Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user profle.\"\"\" current_app.logger.debug(u'Get profile", "by {{AUTHOR}}. :license: BSD, see LICENSE for more details. \"\"\" from flask import", "flask import current_app, render_template, Blueprint from flask_security import login_required blueprint = Blueprint('users', __name__,", "Blueprint from flask_security import login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def", "__name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user profle.\"\"\" current_app.logger.debug(u'Get profile user.') return", "url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user profle.\"\"\" current_app.logger.debug(u'Get profile user.') return render_template('users/profile.html')", "blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user profle.\"\"\" current_app.logger.debug(u'Get", "LICENSE for more details. \"\"\" from flask import current_app, render_template, Blueprint from flask_security", "\"\"\" from flask import current_app, render_template, Blueprint from flask_security import login_required blueprint =", "module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE for more details.", "{{NAME}} user controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE", "from flask import current_app, render_template, Blueprint from flask_security import login_required blueprint = Blueprint('users',", "flask_security import login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return", "from flask_security import login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile():", "Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user profle.\"\"\" current_app.logger.debug(u'Get profile user.')", "see LICENSE for more details. \"\"\" from flask import current_app, render_template, Blueprint from", "(c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE for more details. \"\"\" from", "import current_app, render_template, Blueprint from flask_security import login_required blueprint = Blueprint('users', __name__, url_prefix='/users')", "\"\"\" {{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license:", "details. \"\"\" from flask import current_app, render_template, Blueprint from flask_security import login_required blueprint", "render_template, Blueprint from flask_security import login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required", ":license: BSD, see LICENSE for more details. \"\"\" from flask import current_app, render_template,", "for more details. \"\"\" from flask import current_app, render_template, Blueprint from flask_security import", "-*- \"\"\" {{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}.", "user controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE for", "current_app, render_template, Blueprint from flask_security import login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile')", "controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE for more", "{{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD,", "-*- coding: utf-8 -*- \"\"\" {{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c)", "login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user profle.\"\"\"", "{{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE for more details. \"\"\" from flask", "import login_required blueprint = Blueprint('users', __name__, url_prefix='/users') @blueprint.route('/profile') @login_required def profile(): \"\"\"return user", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see", "BSD, see LICENSE for more details. \"\"\" from flask import current_app, render_template, Blueprint", "coding: utf-8 -*- \"\"\" {{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c) {{YEAR}}", "more details. \"\"\" from flask import current_app, render_template, Blueprint from flask_security import login_required", "utf-8 -*- \"\"\" {{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright: (c) {{YEAR}} by", "{{AUTHOR}}. :license: BSD, see LICENSE for more details. \"\"\" from flask import current_app,", ":copyright: (c) {{YEAR}} by {{AUTHOR}}. :license: BSD, see LICENSE for more details. \"\"\"", "# -*- coding: utf-8 -*- \"\"\" {{NAMEPROJECT}}.users.controllers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{NAME}} user controllers module :copyright:" ]
[ "the src attribute of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def", "int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else: current_speed = 0 # Decode Turn", "rospy # Standard Python Libraries import threading import os import time # Messages", "Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return html def gen(camera):", "return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed, current_turn, write_event #", "direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x = float(current_speed)", "streaming generator function.\"\"\" while True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' +", "function.\"\"\" while True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame +", "0 # Decode Turn if 'turn' in request.args and int(request.args[\"turn\"]) != current_turn: current_turn", "Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed, current_turn, write_event # Decode", "import Camera # Globals current_speed = 0 current_turn = 0 ping_time = 0", "direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return html def gen(camera): \"\"\"Video", "yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming", "pi_drone_server.html import html from pi_drone_server.camera import Camera # Globals current_speed = 0 current_turn", "timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We need to wait", "To ros_thread That New Directions Have Been Received write_event.set() # Return Code 204", "mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed, current_turn, write_event # Decode Speed", "write_event.wait() msg = Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def", "= 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return", "'speed' in request.args and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else: current_speed =", "rospy node to initialize before running. while not rospy.is_shutdown(): if (time.time() - ping_time)", "import Flask, request, Response from pi_drone_server.html import html from pi_drone_server.camera import Camera #", "wait for the rospy node to initialize before running. while not rospy.is_shutdown(): if", "Party Libraries from flask import Flask, request, Response from pi_drone_server.html import html from", "current_turn = 0 ping_time = 0 write_event = threading.Event() app = Flask(__name__) #", "= time.time() return ('', 204) def timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT", "def timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We need to", "b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put", "request.args and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else: current_turn = 0 #", "current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x", "# Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return html def", "tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed, current_turn, write_event", "current_turn, write_event # Decode Speed if 'speed' in request.args and int(request.args[\"speed\"]) != current_speed:", "Turn if 'turn' in request.args and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else:", "= Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def pi_drone_server(): \"\"\"Executable\"\"\"", "True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed')", "html from pi_drone_server.camera import Camera # Globals current_speed = 0 current_turn = 0", "204 return ('', 204) @app.route(\"/ping\") def ping(): global ping_time ping_time = time.time() return", "We need to wait for the rospy node to initialize before running. while", "global ping_time ping_time = time.time() return ('', 204) def timeout_thread(): global ping_time, current_speed,", "!= current_speed: current_speed = request.args[\"speed\"] else: current_speed = 0 # Decode Turn if", "> TIMEOUT: current_speed = 0 current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread(): global", "def video_feed(): \"\"\"Video streaming route. Put this in the src attribute of an", "queue_size=10) @app.route('/') def view(): return html def gen(camera): \"\"\"Video streaming generator function.\"\"\" while", "Put this in the src attribute of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace;", "boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed, current_turn, write_event # Decode Speed if", "@app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put this in the src attribute of", "else: current_speed = 0 # Decode Turn if 'turn' in request.args and int(request.args[\"turn\"])", "# Return Code 204 return ('', 204) @app.route(\"/ping\") def ping(): global ping_time ping_time", "time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown():", "= request.args[\"turn\"] else: current_turn = 0 # Signal To ros_thread That New Directions", "Decode Speed if 'speed' in request.args and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"]", "= 0 current_turn = 0 ping_time = 0 write_event = threading.Event() app =", "import rospy # Standard Python Libraries import threading import os import time #", "current_speed = 0 current_turn = 0 ping_time = 0 write_event = threading.Event() app", "and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else: current_speed = 0 # Decode", "to initialize before running. while not rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT:", "current_turn = request.args[\"turn\"] else: current_turn = 0 # Signal To ros_thread That New", "def ping(): global ping_time ping_time = time.time() return ('', 204) def timeout_thread(): global", "the rospy node to initialize before running. while not rospy.is_shutdown(): if (time.time() -", "Flask, request, Response from pi_drone_server.html import html from pi_drone_server.camera import Camera # Globals", "frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put this in the", "current_speed = 0 current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn,", "That New Directions Have Been Received write_event.set() # Return Code 204 return ('',", "Ros Client import rospy # Standard Python Libraries import threading import os import", "Flask(__name__) # Constants TIMEOUT = 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10)", "ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg", "global direction, current_speed, current_turn, write_event # Decode Speed if 'speed' in request.args and", "# Constants TIMEOUT = 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/')", "write_event.set() # Return Code 204 return ('', 204) @app.route(\"/ping\") def ping(): global ping_time", "current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg = Twist()", "# Third Party Libraries from flask import Flask, request, Response from pi_drone_server.html import", "of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction,", "Been Received write_event.set() # Return Code 204 return ('', 204) @app.route(\"/ping\") def ping():", "(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route.", "import time # Messages from geometry_msgs.msg import Twist # Third Party Libraries from", "request.args[\"speed\"] else: current_speed = 0 # Decode Turn if 'turn' in request.args and", "0 current_turn = 0 ping_time = 0 write_event = threading.Event() app = Flask(__name__)", "Directions Have Been Received write_event.set() # Return Code 204 return ('', 204) @app.route(\"/ping\")", "import Twist # Third Party Libraries from flask import Flask, request, Response from", "view(): return html def gen(camera): \"\"\"Video streaming generator function.\"\"\" while True: frame =", "(time.time() - ping_time) > TIMEOUT: current_speed = 0 current_turn = 0 write_event.set() time.sleep(0.1)", "@app.route(\"/ping\") def ping(): global ping_time ping_time = time.time() return ('', 204) def timeout_thread():", "if (time.time() - ping_time) > TIMEOUT: current_speed = 0 current_turn = 0 write_event.set()", "import html from pi_drone_server.camera import Camera # Globals current_speed = 0 current_turn =", "# We need to wait for the rospy node to initialize before running.", "while not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn)", "= 0 ping_time = 0 write_event = threading.Event() app = Flask(__name__) # Constants", "@app.route('/') def view(): return html def gen(camera): \"\"\"Video streaming generator function.\"\"\" while True:", "0 # Signal To ros_thread That New Directions Have Been Received write_event.set() #", "from pi_drone_server.camera import Camera # Globals current_speed = 0 current_turn = 0 ping_time", "Signal To ros_thread That New Directions Have Been Received write_event.set() # Return Code", "Decode Turn if 'turn' in request.args and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"]", "= float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def pi_drone_server(): \"\"\"Executable\"\"\" threading.Thread(target=ros_thread).start() threading.Thread(target=timeout_thread).start() app.run(host=\"0.0.0.0\",", "direction, current_speed, current_turn, write_event # Decode Speed if 'speed' in request.args and int(request.args[\"speed\"])", "\"\"\"Video streaming generator function.\"\"\" while True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n'", "Code 204 return ('', 204) @app.route(\"/ping\") def ping(): global ping_time ping_time = time.time()", "Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def pi_drone_server(): \"\"\"Executable\"\"\" threading.Thread(target=ros_thread).start()", "in request.args and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else: current_speed = 0", "while not rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT: current_speed = 0 current_turn", "ros_thread That New Directions Have Been Received write_event.set() # Return Code 204 return", "Globals current_speed = 0 current_turn = 0 ping_time = 0 write_event = threading.Event()", "Standard Python Libraries import threading import os import time # Messages from geometry_msgs.msg", "= threading.Event() app = Flask(__name__) # Constants TIMEOUT = 1.5 # Seconds direction", "# Standard Python Libraries import threading import os import time # Messages from", "= camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def video_feed():", "write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x =", "msg = Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def pi_drone_server():", "Received write_event.set() # Return Code 204 return ('', 204) @app.route(\"/ping\") def ping(): global", "request, Response from pi_drone_server.html import html from pi_drone_server.camera import Camera # Globals current_speed", "before running. while not rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT: current_speed =", "camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video", "html def gen(camera): \"\"\"Video streaming generator function.\"\"\" while True: frame = camera.get_frame() yield", "route. Put this in the src attribute of an img tag.\"\"\" return Response(gen(Camera()),", "+ b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put this in the src", "@app.route(\"/control\") def control(): global direction, current_speed, current_turn, write_event # Decode Speed if 'speed'", "Third Party Libraries from flask import Flask, request, Response from pi_drone_server.html import html", "= 0 current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event,", "Speed if 'speed' in request.args and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else:", "in the src attribute of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\")", "def ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait()", "def view(): return html def gen(camera): \"\"\"Video streaming generator function.\"\"\" while True: frame", "if 'speed' in request.args and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else: current_speed", "Return Code 204 return ('', 204) @app.route(\"/ping\") def ping(): global ping_time ping_time =", "TIMEOUT = 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view():", "this in the src attribute of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')", "ping_time ping_time = time.time() return ('', 204) def timeout_thread(): global ping_time, current_speed, current_turn,", "pi_drone_server.camera import Camera # Globals current_speed = 0 current_turn = 0 ping_time =", "from geometry_msgs.msg import Twist # Third Party Libraries from flask import Flask, request,", "# Decode Speed if 'speed' in request.args and int(request.args[\"speed\"]) != current_speed: current_speed =", "image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put this", "= 0 # Decode Turn if 'turn' in request.args and int(request.args[\"turn\"]) != current_turn:", "if 'turn' in request.args and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else: current_turn", "current_speed = request.args[\"speed\"] else: current_speed = 0 # Decode Turn if 'turn' in", "Libraries import threading import os import time # Messages from geometry_msgs.msg import Twist", "streaming route. Put this in the src attribute of an img tag.\"\"\" return", "# Decode Turn if 'turn' in request.args and int(request.args[\"turn\"]) != current_turn: current_turn =", "current_turn: current_turn = request.args[\"turn\"] else: current_turn = 0 # Signal To ros_thread That", "current_speed = 0 # Decode Turn if 'turn' in request.args and int(request.args[\"turn\"]) !=", "204) def timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We need", "rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear()", "\"\"\"Video streaming route. Put this in the src attribute of an img tag.\"\"\"", "import threading import os import time # Messages from geometry_msgs.msg import Twist #", "rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x = float(current_speed) msg.angular.z", "img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed, current_turn,", "!= current_turn: current_turn = request.args[\"turn\"] else: current_turn = 0 # Signal To ros_thread", "generator function.\"\"\" while True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame", "Twist, queue_size=10) @app.route('/') def view(): return html def gen(camera): \"\"\"Video streaming generator function.\"\"\"", "not rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT: current_speed = 0 current_turn =", "return ('', 204) def timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) #", "current_turn, write_event, TIMEOUT time.sleep(1) # We need to wait for the rospy node", "from pi_drone_server.html import html from pi_drone_server.camera import Camera # Globals current_speed = 0", "else: current_turn = 0 # Signal To ros_thread That New Directions Have Been", "Camera # Globals current_speed = 0 current_turn = 0 ping_time = 0 write_event", "def control(): global direction, current_speed, current_turn, write_event # Decode Speed if 'speed' in", "to wait for the rospy node to initialize before running. while not rospy.is_shutdown():", "Libraries from flask import Flask, request, Response from pi_drone_server.html import html from pi_drone_server.camera", "control(): global direction, current_speed, current_turn, write_event # Decode Speed if 'speed' in request.args", "os import time # Messages from geometry_msgs.msg import Twist # Third Party Libraries", "Response from pi_drone_server.html import html from pi_drone_server.camera import Camera # Globals current_speed =", "# Globals current_speed = 0 current_turn = 0 ping_time = 0 write_event =", "current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server',", "time.time() return ('', 204) def timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1)", "= Flask(__name__) # Constants TIMEOUT = 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist,", "write_event, TIMEOUT time.sleep(1) # We need to wait for the rospy node to", "threading import os import time # Messages from geometry_msgs.msg import Twist # Third", "request.args and int(request.args[\"speed\"]) != current_speed: current_speed = request.args[\"speed\"] else: current_speed = 0 #", "attribute of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global", "= 0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True)", "gen(camera): \"\"\"Video streaming generator function.\"\"\" while True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type:", "Python Libraries import threading import os import time # Messages from geometry_msgs.msg import", "def gen(camera): \"\"\"Video streaming generator function.\"\"\" while True: frame = camera.get_frame() yield (b'--frame\\r\\n'", "int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else: current_turn = 0 # Signal To", "204) @app.route(\"/ping\") def ping(): global ping_time ping_time = time.time() return ('', 204) def", "for the rospy node to initialize before running. while not rospy.is_shutdown(): if (time.time()", "('', 204) @app.route(\"/ping\") def ping(): global ping_time ping_time = time.time() return ('', 204)", "geometry_msgs.msg import Twist # Third Party Libraries from flask import Flask, request, Response", "New Directions Have Been Received write_event.set() # Return Code 204 return ('', 204)", "- ping_time) > TIMEOUT: current_speed = 0 current_turn = 0 write_event.set() time.sleep(0.1) def", "ping_time) > TIMEOUT: current_speed = 0 current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread():", "Have Been Received write_event.set() # Return Code 204 return ('', 204) @app.route(\"/ping\") def", "write_event # Decode Speed if 'speed' in request.args and int(request.args[\"speed\"]) != current_speed: current_speed", "# Signal To ros_thread That New Directions Have Been Received write_event.set() # Return", "in request.args and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else: current_turn = 0", "time.sleep(1) # We need to wait for the rospy node to initialize before", "global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg =", "ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We need to wait for the", "TIMEOUT: current_speed = 0 current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed,", "1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return html", "= 0 write_event = threading.Event() app = Flask(__name__) # Constants TIMEOUT = 1.5", "while True: frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')", "write_event = threading.Event() app = Flask(__name__) # Constants TIMEOUT = 1.5 # Seconds", "b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put this in the src attribute", "threading.Event() app = Flask(__name__) # Constants TIMEOUT = 1.5 # Seconds direction =", "current_speed, current_turn, write_event # Decode Speed if 'speed' in request.args and int(request.args[\"speed\"]) !=", "msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def pi_drone_server(): \"\"\"Executable\"\"\" threading.Thread(target=ros_thread).start() threading.Thread(target=timeout_thread).start()", "= rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return html def gen(camera): \"\"\"Video streaming", "+ frame + b'\\r\\n') @app.route('/video_feed') def video_feed(): \"\"\"Video streaming route. Put this in", "= 0 # Signal To ros_thread That New Directions Have Been Received write_event.set()", "write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while not", "return html def gen(camera): \"\"\"Video streaming generator function.\"\"\" while True: frame = camera.get_frame()", "current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We need to wait for the rospy", "initialize before running. while not rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT: current_speed", "import os import time # Messages from geometry_msgs.msg import Twist # Third Party", "ping(): global ping_time ping_time = time.time() return ('', 204) def timeout_thread(): global ping_time,", "TIMEOUT time.sleep(1) # We need to wait for the rospy node to initialize", "current_turn = 0 # Signal To ros_thread That New Directions Have Been Received", "ping_time = time.time() return ('', 204) def timeout_thread(): global ping_time, current_speed, current_turn, write_event,", "disable_signals=True) while not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x = float(current_speed) msg.angular.z =", "frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/video_feed') def", "src attribute of an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control():", "request.args[\"turn\"] else: current_turn = 0 # Signal To ros_thread That New Directions Have", "need to wait for the rospy node to initialize before running. while not", "flask import Flask, request, Response from pi_drone_server.html import html from pi_drone_server.camera import Camera", "float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg) write_event.clear() def pi_drone_server(): \"\"\"Executable\"\"\" threading.Thread(target=ros_thread).start() threading.Thread(target=timeout_thread).start() app.run(host=\"0.0.0.0\", threaded=True)", "'turn' in request.args and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else: current_turn =", "Client import rospy # Standard Python Libraries import threading import os import time", "return ('', 204) @app.route(\"/ping\") def ping(): global ping_time ping_time = time.time() return ('',", "('', 204) def timeout_thread(): global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We", "0 current_turn = 0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event, direction", "# Ros Client import rospy # Standard Python Libraries import threading import os", "ping_time = 0 write_event = threading.Event() app = Flask(__name__) # Constants TIMEOUT =", "rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT: current_speed = 0 current_turn = 0", "# Messages from geometry_msgs.msg import Twist # Third Party Libraries from flask import", "and int(request.args[\"turn\"]) != current_turn: current_turn = request.args[\"turn\"] else: current_turn = 0 # Signal", "Constants TIMEOUT = 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def", "running. while not rospy.is_shutdown(): if (time.time() - ping_time) > TIMEOUT: current_speed = 0", "video_feed(): \"\"\"Video streaming route. Put this in the src attribute of an img", "Messages from geometry_msgs.msg import Twist # Third Party Libraries from flask import Flask,", "0 write_event.set() time.sleep(0.1) def ros_thread(): global current_speed, current_turn, write_event, direction rospy.init_node('pi_drone_server', disable_signals=True) while", "an img tag.\"\"\" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route(\"/control\") def control(): global direction, current_speed,", "not rospy.is_shutdown(): write_event.wait() msg = Twist() msg.linear.x = float(current_speed) msg.angular.z = float(current_turn) direction.publish(msg)", "Twist # Third Party Libraries from flask import Flask, request, Response from pi_drone_server.html", "node to initialize before running. while not rospy.is_shutdown(): if (time.time() - ping_time) >", "time # Messages from geometry_msgs.msg import Twist # Third Party Libraries from flask", "app = Flask(__name__) # Constants TIMEOUT = 1.5 # Seconds direction = rospy.Publisher(\"robot_twist\",", "0 ping_time = 0 write_event = threading.Event() app = Flask(__name__) # Constants TIMEOUT", "rospy.Publisher(\"robot_twist\", Twist, queue_size=10) @app.route('/') def view(): return html def gen(camera): \"\"\"Video streaming generator", "= request.args[\"speed\"] else: current_speed = 0 # Decode Turn if 'turn' in request.args", "from flask import Flask, request, Response from pi_drone_server.html import html from pi_drone_server.camera import", "0 write_event = threading.Event() app = Flask(__name__) # Constants TIMEOUT = 1.5 #", "current_speed: current_speed = request.args[\"speed\"] else: current_speed = 0 # Decode Turn if 'turn'", "global ping_time, current_speed, current_turn, write_event, TIMEOUT time.sleep(1) # We need to wait for" ]
[ "PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a", "self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) if __name__ == '__main__':", "a Python installation that have GDAL installed because OGR module is being used.", "os import unittest import pkgutil from context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE,", "contains domains, tables, and feature classes. This test case is supposed to be", "print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) if __name__ == '__main__': unittest.main()", "= registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path,", "coding: UTF-8 -*- \"\"\"Advanced tests generating html files for a geodatabase. Geodatabase contains", "This test case is supposed to be run with a Python installation that", "self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual(", "= registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path,", "with a Python installation that have GDAL installed because OGR module is being", "UTF-8 -*- \"\"\"Advanced tests generating html files for a geodatabase. Geodatabase contains domains,", "# --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\" test_name = self.id().split('.')[-1]", "report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name +", "a file geodatabase from .xml schema file and load .json look-up data. \"\"\"", "has domains, tables, and feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up", "out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True,", "for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION),", "def test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter =", "test case with a complete geodatabase. Geodatabase contains has domains, tables, and feature", ") self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def", "html files for a geodatabase. Geodatabase contains domains, tables, and feature classes. This", "from context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class", "domains, tables, and feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the", "look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results", "# --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test context. Create a file geodatabase", "--------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter", "import unittest import pkgutil from context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, )", "Geodatabase contains domains, tables, and feature classes. This test case is supposed to", "def setUp(self): \"\"\"Set up the test context. Create a file geodatabase from .xml", "generating html files for a geodatabase. Geodatabase contains domains, tables, and feature classes.", "\"\"\"Set up the test context. Create a file geodatabase from .xml schema file", ".json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder,", "def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter(", "tables, and feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test", "self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_tables(self):", "used. \"\"\" from __future__ import print_function import os import unittest import pkgutil from", "a geodatabase. Geodatabase contains domains, tables, and feature classes. This test case is", "registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results,", "\"\"\" from __future__ import print_function import os import unittest import pkgutil from context", "), (True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\"", "self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual(", "self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for", "# -*- coding: UTF-8 -*- \"\"\"Advanced tests generating html files for a geodatabase.", "<reponame>dersteppenwolf/registrant<filename>tests/test_reporter_advanced_ogr.py # -*- coding: UTF-8 -*- \"\"\"Advanced tests generating html files for a", "domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), )", "import os import unittest import pkgutil from context import ( registrant, prepare_test, PYTHON_VERSION,", "feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test context. Create", "-*- coding: UTF-8 -*- \"\"\"Advanced tests generating html files for a geodatabase. Geodatabase", "# --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter", "from __future__ import print_function import os import unittest import pkgutil from context import", "context. Create a file geodatabase from .xml schema file and load .json look-up", "PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # ---------------------------------------------------------------------", "html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete geodatabase. Geodatabase contains", "\"\"\"Test geodatabase report for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb,", "\"\"\"Full test case with a complete geodatabase. Geodatabase contains has domains, tables, and", "= pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') #", "feature classes. This test case is supposed to be run with a Python", "test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb,", "tests generating html files for a geodatabase. Geodatabase contains domains, tables, and feature", ") self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def", "supposed to be run with a Python installation that have GDAL installed because", "test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter(", ") self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) if __name__ ==", "json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for feature", "prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with", "is supposed to be run with a Python installation that have GDAL installed", "Geodatabase contains has domains, tables, and feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self):", "prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name =", "ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr')", "( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test", "= self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path)", "json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\"", "test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True))", "classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), )", "SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete geodatabase. Geodatabase contains has domains, tables,", "with a complete geodatabase. Geodatabase contains has domains, tables, and feature classes. \"\"\"", "NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete", "geodatabase. Geodatabase contains domains, tables, and feature classes. This test case is supposed", "case with a complete geodatabase. Geodatabase contains has domains, tables, and feature classes.", "= prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name", "), (True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name", "registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case", "pkgutil from context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ########################################################################", "class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete geodatabase. Geodatabase contains has domains,", "\"\"\"Test geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder,", "html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report", "the test context. Create a file geodatabase from .xml schema file and load", "case is supposed to be run with a Python installation that have GDAL", "\"\"\"Advanced tests generating html files for a geodatabase. Geodatabase contains domains, tables, and", "print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test", "test case is supposed to be run with a Python installation that have", "out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True,", "contains has domains, tables, and feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set", "context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase):", "run with a Python installation that have GDAL installed because OGR module is", "OGR module is being used. \"\"\" from __future__ import print_function import os import", "module is being used. \"\"\" from __future__ import print_function import os import unittest", "classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test context. Create a", "installed because OGR module is being used. \"\"\" from __future__ import print_function import", "test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True))", "__future__ import print_function import os import unittest import pkgutil from context import (", "True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1]", "+ PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) #", "and load .json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE)", "import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete geodatabase. Geodatabase", "registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results,", "file geodatabase from .xml schema file and load .json look-up data. \"\"\" ogr_loader", "geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name", "tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), )", "import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full", "ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test", "test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html()", "-*- \"\"\"Advanced tests generating html files for a geodatabase. Geodatabase contains domains, tables,", "being used. \"\"\" from __future__ import print_function import os import unittest import pkgutil", "and feature classes. \"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test context.", "self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html(", "--------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test context. Create a file geodatabase from", "and feature classes. This test case is supposed to be run with a", "be run with a Python installation that have GDAL installed because OGR module", "import print_function import os import unittest import pkgutil from context import ( registrant,", "print_function import os import unittest import pkgutil from context import ( registrant, prepare_test,", "True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\" test_name =", "gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ),", "html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report", "self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\"", "self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual(", "Python installation that have GDAL installed because OGR module is being used. \"\"\"", "complete geodatabase. Geodatabase contains has domains, tables, and feature classes. \"\"\" # ---------------------------------------------------------------------", "domains, tables, and feature classes. This test case is supposed to be run", "geodatabase report for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder,", "registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results,", "is being used. \"\"\" from __future__ import print_function import os import unittest import", "self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html(", "self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase", "file and load .json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader:", "= self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html() print(self.reporter.report_file_path)", "that have GDAL installed because OGR module is being used. \"\"\" from __future__", "GDAL installed because OGR module is being used. \"\"\" from __future__ import print_function", "from .xml schema file and load .json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr')", "pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # ---------------------------------------------------------------------", "for a geodatabase. Geodatabase contains domains, tables, and feature classes. This test case", "--------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter =", "print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test", "self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase", "--------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter =", "geodatabase from .xml schema file and load .json look-up data. \"\"\" ogr_loader =", "self.reporter.tables2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_tables_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_fcs(self):", "geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name", "(True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for feature classes.\"\"\" test_name", "installation that have GDAL installed because OGR module is being used. \"\"\" from", "report for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name", "+ PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) if", "gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ),", "load .json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb,", "######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete geodatabase. Geodatabase contains has", "for feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name +", "setUp(self): \"\"\"Set up the test context. Create a file geodatabase from .xml schema", "\"\"\" # --------------------------------------------------------------------- def setUp(self): \"\"\"Set up the test context. Create a file", "for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION),", "schema file and load .json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not", "PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # ---------------------------------------------------------------------", "html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for", "+ PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) #", "self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase", "gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ),", "report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name +", "have GDAL installed because OGR module is being used. \"\"\" from __future__ import", "unittest import pkgutil from context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import", "PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) if __name__", "classes. This test case is supposed to be run with a Python installation", ") import html_parsers ######################################################################## class SimpleGeodatabase(unittest.TestCase): \"\"\"Full test case with a complete geodatabase.", "feature classes.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION),", "self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_domains_from_html(", "to be run with a Python installation that have GDAL installed because OGR", "if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def", "tables, and feature classes. This test case is supposed to be run with", "html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True)) # --------------------------------------------------------------------- def test_fcs(self): \"\"\"Test geodatabase report for", "def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter(", "up the test context. Create a file geodatabase from .xml schema file and", "self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report", "test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True, True))", "'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self): \"\"\"Test geodatabase report for domains.\"\"\" test_name = self.id().split('.')[-1]", "\"\"\"Test geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder,", "test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.tables2html()", "geodatabase. Geodatabase contains has domains, tables, and feature classes. \"\"\" # --------------------------------------------------------------------- def", "test context. Create a file geodatabase from .xml schema file and load .json", "# --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter", "not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test( 'Advanced_ogr') # --------------------------------------------------------------------- def test_domains(self):", "test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html()", "test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name = self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb,", "out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path, json_file=self.json_results, ), (True,", "\"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results = prepare_test(", "= self.id().split('.')[-1] self.reporter = registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.domains2html() print(self.reporter.report_file_path)", "= registrant.Reporter( gdb_path=self.in_gdb, out_report_folder_path=os.path.join(self.out_report_folder, test_name + PYTHON_VERSION), ) self.reporter.fcs2html() print(self.reporter.report_file_path) self.assertEqual( html_parsers.parse_fcs_from_html( html_file=self.reporter.report_file_path,", "files for a geodatabase. Geodatabase contains domains, tables, and feature classes. This test", "because OGR module is being used. \"\"\" from __future__ import print_function import os", "a complete geodatabase. Geodatabase contains has domains, tables, and feature classes. \"\"\" #", "Create a file geodatabase from .xml schema file and load .json look-up data.", "data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if not ogr_loader: self.skipTest(NO_OGR_ENV_MESSAGE) self.in_gdb, self.out_report_folder, self.json_results =", "(True, True)) # --------------------------------------------------------------------- def test_tables(self): \"\"\"Test geodatabase report for tables.\"\"\" test_name =", ".xml schema file and load .json look-up data. \"\"\" ogr_loader = pkgutil.find_loader('ogr') if", "import pkgutil from context import ( registrant, prepare_test, PYTHON_VERSION, NO_OGR_ENV_MESSAGE, ) import html_parsers" ]
[ "\"uk\" link_list = [row for row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html", "# -*- mode:python; coding:utf-8; -*- from sqlalchemy import create_engine from html_templates import html_begin,", "import mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang", "mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not", "lang not in (\"ru\", \"en\"): lang = \"uk\" link_list = [row for row", "in (\"ru\", \"en\"): lang = \"uk\" link_list = [row for row in e.execute(\"select", "= \"uk\" link_list = [row for row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))]", "from links\".format(l=lang))] html = html_begin for record in link_list: html += html_links_li.format(link=record[0], desc=record[1])", "if lang not in (\"ru\", \"en\"): lang = \"uk\" link_list = [row for", "lang = \"uk\" link_list = [row for row in e.execute(\"select uri, desc_{l} from", "= [\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not in (\"ru\",", "-*- from sqlalchemy import create_engine from html_templates import html_begin, html_end, html_links_li from mysql", "in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html = html_begin for record in link_list:", "sqlalchemy import create_engine from html_templates import html_begin, html_end, html_links_li from mysql import mysql_connect_data", "html_templates import html_begin, html_end, html_links_li from mysql import mysql_connect_data __all__ = [\"links\"] def", "desc_{l} from links\".format(l=lang))] html = html_begin for record in link_list: html += html_links_li.format(link=record[0],", "(\"ru\", \"en\"): lang = \"uk\" link_list = [row for row in e.execute(\"select uri,", "= [row for row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html = html_begin", "html_links_li from mysql import mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e =", "row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html = html_begin for record in", "\"en\"): lang = \"uk\" link_list = [row for row in e.execute(\"select uri, desc_{l}", "def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not in (\"ru\", \"en\"): lang", "-*- mode:python; coding:utf-8; -*- from sqlalchemy import create_engine from html_templates import html_begin, html_end,", "import html_begin, html_end, html_links_li from mysql import mysql_connect_data __all__ = [\"links\"] def links(lang,", "from mysql import mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data)", "import create_engine from html_templates import html_begin, html_end, html_links_li from mysql import mysql_connect_data __all__", "e = create_engine(connect_data) if lang not in (\"ru\", \"en\"): lang = \"uk\" link_list", "links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not in (\"ru\", \"en\"): lang =", "create_engine from html_templates import html_begin, html_end, html_links_li from mysql import mysql_connect_data __all__ =", "mode:python; coding:utf-8; -*- from sqlalchemy import create_engine from html_templates import html_begin, html_end, html_links_li", "= create_engine(connect_data) if lang not in (\"ru\", \"en\"): lang = \"uk\" link_list =", "[\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not in (\"ru\", \"en\"):", "not in (\"ru\", \"en\"): lang = \"uk\" link_list = [row for row in", "uri, desc_{l} from links\".format(l=lang))] html = html_begin for record in link_list: html +=", "[row for row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html = html_begin for", "e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html = html_begin for record in link_list: html", "html_begin for record in link_list: html += html_links_li.format(link=record[0], desc=record[1]) return html + html_end", "html = html_begin for record in link_list: html += html_links_li.format(link=record[0], desc=record[1]) return html", "create_engine(connect_data) if lang not in (\"ru\", \"en\"): lang = \"uk\" link_list = [row", "links\".format(l=lang))] html = html_begin for record in link_list: html += html_links_li.format(link=record[0], desc=record[1]) return", "coding:utf-8; -*- from sqlalchemy import create_engine from html_templates import html_begin, html_end, html_links_li from", "__all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not in", "mysql import mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e = create_engine(connect_data) if", "from html_templates import html_begin, html_end, html_links_li from mysql import mysql_connect_data __all__ = [\"links\"]", "html_end, html_links_li from mysql import mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data): e", "link_list = [row for row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html =", "html_begin, html_end, html_links_li from mysql import mysql_connect_data __all__ = [\"links\"] def links(lang, connect_data=mysql_connect_data):", "from sqlalchemy import create_engine from html_templates import html_begin, html_end, html_links_li from mysql import", "for row in e.execute(\"select uri, desc_{l} from links\".format(l=lang))] html = html_begin for record", "connect_data=mysql_connect_data): e = create_engine(connect_data) if lang not in (\"ru\", \"en\"): lang = \"uk\"", "= html_begin for record in link_list: html += html_links_li.format(link=record[0], desc=record[1]) return html +" ]
[ "incidence_rate_ci, risk_ratio, risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes,", "number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity, specificity, ppv_converter,", "attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity, specificity, ppv_converter, npv_converter, screening_cost_analyzer, rubins_rules, s_value)", "incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity, specificity, ppv_converter, npv_converter, screening_cost_analyzer,", "risk_ratio, risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity,", ".utils import (risk_ci, incidence_rate_ci, risk_ratio, risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds,", "incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity, specificity, ppv_converter, npv_converter, screening_cost_analyzer, rubins_rules,", "odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity, specificity, ppv_converter, npv_converter,", "import (risk_ci, incidence_rate_ci, risk_ratio, risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability,", "(risk_ci, incidence_rate_ci, risk_ratio, risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue,", "from .utils import (risk_ci, incidence_rate_ci, risk_ratio, risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction,", "risk_difference, number_needed_to_treat, odds_ratio, incidence_rate_ratio, incidence_rate_difference, attributable_community_risk, population_attributable_fraction, probability_to_odds, odds_to_probability, counternull_pvalue, semibayes, sensitivity, specificity," ]
[ "def __init__(self, path: str, uuid_str: str = None): self._uuid = uuid_str if uuid_str", "self._status def set_status(self, status: StorageItemStatus): self._status = status def _calc_hash(self): if self._path is", "UNKNOWN = 'Unknown' ON_TARGET = 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload", "file, or non-media file import abc import hashlib import os import uuid from", "hash(self): return self._hash def status(self): return self._status def set_status(self, status: StorageItemStatus): self._status =", "import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On Target' UPLOADING =", "'Unknown' ON_TARGET = 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED", "self._path def hash(self): return self._hash def status(self): return self._status def set_status(self, status: StorageItemStatus):", "f'{b:02x}' self._hash = digest_str # class Directory(StorageItem): # def __init__(self, path: str): #", "File(StorageItem): def __init__(self, path: str, uuid_str: str = None): super(File, self).__init__(path, uuid_str) def", "__init__(self, path: str, uuid_str: str = None): self._uuid = uuid_str if uuid_str else", "def __init__(self, path: str, uuid_str: str = None): super(File, self).__init__(path, uuid_str) def is_dir(self):", "self._hash = None return h = hashlib.sha256() if not self.is_dir(): b = bytearray(256", "self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self): return self._uuid def path(self):", "status def _calc_hash(self): if self._path is None or self._path == '': self._hash =", "UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def", "str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self):", "uuid_str: str = None): self._uuid = uuid_str if uuid_str else str(uuid.uuid1()) self._path =", "path: str, uuid_str: str = None): self._uuid = uuid_str if uuid_str else str(uuid.uuid1())", "str = None): super(File, self).__init__(path, uuid_str) def is_dir(self): return False class MediaFile(File): def", "bytearray(256 * 1024) mv = memoryview(b) with open(self._path, 'rb', buffering=0) as f: for", "from enum import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On Target'", "= hashlib.sha256() if not self.is_dir(): b = bytearray(256 * 1024) mv = memoryview(b)", "'' for b in digest: digest_str += f'{b:02x}' self._hash = digest_str # class", "def is_dir(self): # return True class File(StorageItem): def __init__(self, path: str, uuid_str: str", "or non-media file import abc import hashlib import os import uuid from enum", "import os import uuid from enum import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown'", "self.is_dir(): b = bytearray(256 * 1024) mv = memoryview(b) with open(self._path, 'rb', buffering=0)", "None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self): return self._uuid def", "class Directory(StorageItem): # def __init__(self, path: str): # super(Directory, self).__init__(path) # # def", "self._uuid def path(self): return self._path def hash(self): return self._hash def status(self): return self._status", "def is_dir(self): pass def uuid(self): return self._uuid def path(self): return self._path def hash(self):", "self._path == '': self._hash = None return h = hashlib.sha256() if not self.is_dir():", "that used by Storage; # can be either a directory or media file,", "+= f'{b:02x}' self._hash = digest_str # class Directory(StorageItem): # def __init__(self, path: str):", "os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self):", "os import uuid from enum import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET", "= 'Unknown' ON_TARGET = 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed'", "= h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = '' for b in", "be either a directory or media file, or non-media file import abc import", "= 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self,", "either a directory or media file, or non-media file import abc import hashlib", "in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest()", "n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest =", "uuid from enum import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On", "# def is_dir(self): # return True class File(StorageItem): def __init__(self, path: str, uuid_str:", "self).__init__(path, uuid_str) def is_dir(self): return False class MediaFile(File): def __init__(self, path: str, uuid_str:", "return self._status def set_status(self, status: StorageItemStatus): self._status = status def _calc_hash(self): if self._path", "a directory or media file, or non-media file import abc import hashlib import", "uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod", "# super(Directory, self).__init__(path) # # def is_dir(self): # return True class File(StorageItem): def", "represents items that used by Storage; # can be either a directory or", "= StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self): return self._uuid def path(self): return", "self._hash def status(self): return self._status def set_status(self, status: StorageItemStatus): self._status = status def", "# class Directory(StorageItem): # def __init__(self, path: str): # super(Directory, self).__init__(path) # #", "MediaFile(File): def __init__(self, path: str, uuid_str: str = None): super(MediaFile, self).__init__(path, uuid_str) self._calc_hash()", "can be either a directory or media file, or non-media file import abc", "_calc_hash(self): if self._path is None or self._path == '': self._hash = None return", "self._uuid = uuid_str if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None", "= 'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str:", "h = hashlib.sha256() if not self.is_dir(): b = bytearray(256 * 1024) mv =", "def __init__(self, path: str): # super(Directory, self).__init__(path) # # def is_dir(self): # return", "super(Directory, self).__init__(path) # # def is_dir(self): # return True class File(StorageItem): def __init__(self,", "memoryview(b) with open(self._path, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0):", "self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self): return", "= digest_str # class Directory(StorageItem): # def __init__(self, path: str): # super(Directory, self).__init__(path)", "'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash =", "is_dir(self): return False class MediaFile(File): def __init__(self, path: str, uuid_str: str = None):", "hashlib import os import uuid from enum import Enum class StorageItemStatus(Enum): UNKNOWN =", "self._hash = digest_str # class Directory(StorageItem): # def __init__(self, path: str): # super(Directory,", "digest_str # class Directory(StorageItem): # def __init__(self, path: str): # super(Directory, self).__init__(path) #", "or media file, or non-media file import abc import hashlib import os import", "abc import hashlib import os import uuid from enum import Enum class StorageItemStatus(Enum):", "f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str =", "self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = '' for b", "is_dir(self): # return True class File(StorageItem): def __init__(self, path: str, uuid_str: str =", "Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On Target' UPLOADING = 'Uploading'", "def uuid(self): return self._uuid def path(self): return self._path def hash(self): return self._hash def", "digest_str += f'{b:02x}' self._hash = digest_str # class Directory(StorageItem): # def __init__(self, path:", "= h.digest() digest_str = '' for b in digest: digest_str += f'{b:02x}' self._hash", "StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED =", "hashlib.sha256() if not self.is_dir(): b = bytearray(256 * 1024) mv = memoryview(b) with", "'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str = None): self._uuid =", "class MediaFile(File): def __init__(self, path: str, uuid_str: str = None): super(MediaFile, self).__init__(path, uuid_str)", "not self.is_dir(): b = bytearray(256 * 1024) mv = memoryview(b) with open(self._path, 'rb',", "return True class File(StorageItem): def __init__(self, path: str, uuid_str: str = None): super(File,", "uuid_str if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None self._status =", "str, uuid_str: str = None): self._uuid = uuid_str if uuid_str else str(uuid.uuid1()) self._path", "None return h = hashlib.sha256() if not self.is_dir(): b = bytearray(256 * 1024)", "= None): self._uuid = uuid_str if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash", "= 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str = None): self._uuid", "# # def is_dir(self): # return True class File(StorageItem): def __init__(self, path: str,", "h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = '' for", "= uuid_str if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None self._status", "by Storage; # can be either a directory or media file, or non-media", "Storage; # can be either a directory or media file, or non-media file", "import hashlib import os import uuid from enum import Enum class StorageItemStatus(Enum): UNKNOWN", "def set_status(self, status: StorageItemStatus): self._status = status def _calc_hash(self): if self._path is None", "UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str,", "self._path is None or self._path == '': self._hash = None return h =", "def path(self): return self._path def hash(self): return self._hash def status(self): return self._status def", "return self._hash def status(self): return self._status def set_status(self, status: StorageItemStatus): self._status = status", "1024) mv = memoryview(b) with open(self._path, 'rb', buffering=0) as f: for n in", "for b in digest: digest_str += f'{b:02x}' self._hash = digest_str # class Directory(StorageItem):", "else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = '' for b in digest: digest_str", "uuid_str: str = None): super(File, self).__init__(path, uuid_str) def is_dir(self): return False class MediaFile(File):", "class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED", "str = None): self._uuid = uuid_str if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path)", "None): self._uuid = uuid_str if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash =", "b in digest: digest_str += f'{b:02x}' self._hash = digest_str # class Directory(StorageItem): #", "uuid_str) def is_dir(self): return False class MediaFile(File): def __init__(self, path: str, uuid_str: str", "else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def", "return h = hashlib.sha256() if not self.is_dir(): b = bytearray(256 * 1024) mv", "digest: digest_str += f'{b:02x}' self._hash = digest_str # class Directory(StorageItem): # def __init__(self,", "import abc import hashlib import os import uuid from enum import Enum class", "status(self): return self._status def set_status(self, status: StorageItemStatus): self._status = status def _calc_hash(self): if", "if not self.is_dir(): b = bytearray(256 * 1024) mv = memoryview(b) with open(self._path,", "None): super(File, self).__init__(path, uuid_str) def is_dir(self): return False class MediaFile(File): def __init__(self, path:", "= status def _calc_hash(self): if self._path is None or self._path == '': self._hash", "for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest", "self).__init__(path) # # def is_dir(self): # return True class File(StorageItem): def __init__(self, path:", "@abc.abstractmethod def is_dir(self): pass def uuid(self): return self._uuid def path(self): return self._path def", "def hash(self): return self._hash def status(self): return self._status def set_status(self, status: StorageItemStatus): self._status", "= None): super(File, self).__init__(path, uuid_str) def is_dir(self): return False class MediaFile(File): def __init__(self,", "self._path = os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass", "'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path:", "= 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded'", "mv = memoryview(b) with open(self._path, 'rb', buffering=0) as f: for n in iter(lambda:", "open(self._path, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash", "super(File, self).__init__(path, uuid_str) def is_dir(self): return False class MediaFile(File): def __init__(self, path: str,", "h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = '' for b in digest:", "non-media file import abc import hashlib import os import uuid from enum import", "= bytearray(256 * 1024) mv = memoryview(b) with open(self._path, 'rb', buffering=0) as f:", "= os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def", "True class File(StorageItem): def __init__(self, path: str, uuid_str: str = None): super(File, self).__init__(path,", "# def __init__(self, path: str): # super(Directory, self).__init__(path) # # def is_dir(self): #", "is None or self._path == '': self._hash = None return h = hashlib.sha256()", "Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC):", "pass def uuid(self): return self._uuid def path(self): return self._path def hash(self): return self._hash", "path: str): # super(Directory, self).__init__(path) # # def is_dir(self): # return True class", "or self._path == '': self._hash = None return h = hashlib.sha256() if not", "status: StorageItemStatus): self._status = status def _calc_hash(self): if self._path is None or self._path", "if self._path is None or self._path == '': self._hash = None return h", "iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str", "__init__(self, path: str): # super(Directory, self).__init__(path) # # def is_dir(self): # return True", "file import abc import hashlib import os import uuid from enum import Enum", "= None self._status = StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self): return self._uuid", "self._status = status def _calc_hash(self): if self._path is None or self._path == '':", "def status(self): return self._status def set_status(self, status: StorageItemStatus): self._status = status def _calc_hash(self):", "str, uuid_str: str = None): super(File, self).__init__(path, uuid_str) def is_dir(self): return False class", "set_status(self, status: StorageItemStatus): self._status = status def _calc_hash(self): if self._path is None or", "class File(StorageItem): def __init__(self, path: str, uuid_str: str = None): super(File, self).__init__(path, uuid_str)", "== '': self._hash = None return h = hashlib.sha256() if not self.is_dir(): b", "return self._path def hash(self): return self._hash def status(self): return self._status def set_status(self, status:", "None or self._path == '': self._hash = None return h = hashlib.sha256() if", "digest = h.digest() digest_str = '' for b in digest: digest_str += f'{b:02x}'", "def is_dir(self): return False class MediaFile(File): def __init__(self, path: str, uuid_str: str =", "UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str = None):", "0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = ''", "False class MediaFile(File): def __init__(self, path: str, uuid_str: str = None): super(MediaFile, self).__init__(path,", "uuid(self): return self._uuid def path(self): return self._path def hash(self): return self._hash def status(self):", "StorageItemStatus.UNKNOWN @abc.abstractmethod def is_dir(self): pass def uuid(self): return self._uuid def path(self): return self._path", "items that used by Storage; # can be either a directory or media", "ON_TARGET = 'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED =", "return self._uuid def path(self): return self._path def hash(self): return self._hash def status(self): return", "as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else:", "enum import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET = 'On Target' UPLOADING", "buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest()", "h.digest() digest_str = '' for b in digest: digest_str += f'{b:02x}' self._hash =", "__init__(self, path: str, uuid_str: str = None): super(File, self).__init__(path, uuid_str) def is_dir(self): return", "def _calc_hash(self): if self._path is None or self._path == '': self._hash = None", "= None return h = hashlib.sha256() if not self.is_dir(): b = bytearray(256 *", "digest_str = '' for b in digest: digest_str += f'{b:02x}' self._hash = digest_str", "path(self): return self._path def hash(self): return self._hash def status(self): return self._status def set_status(self,", "Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str =", "StorageItemStatus): self._status = status def _calc_hash(self): if self._path is None or self._path ==", "'': self._hash = None return h = hashlib.sha256() if not self.is_dir(): b =", "in digest: digest_str += f'{b:02x}' self._hash = digest_str # class Directory(StorageItem): # def", "b = bytearray(256 * 1024) mv = memoryview(b) with open(self._path, 'rb', buffering=0) as", "used by Storage; # can be either a directory or media file, or", "'Upload Failed' UPLOADED = 'Uploaded' class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str", "is_dir(self): pass def uuid(self): return self._uuid def path(self): return self._path def hash(self): return", "directory or media file, or non-media file import abc import hashlib import os", "f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) self._hash = h.hexdigest() else: h.update(os.path.abspath(self._path))", "return False class MediaFile(File): def __init__(self, path: str, uuid_str: str = None): super(MediaFile,", "Directory(StorageItem): # def __init__(self, path: str): # super(Directory, self).__init__(path) # # def is_dir(self):", "# return True class File(StorageItem): def __init__(self, path: str, uuid_str: str = None):", "* 1024) mv = memoryview(b) with open(self._path, 'rb', buffering=0) as f: for n", "if uuid_str else str(uuid.uuid1()) self._path = os.path.abspath(path) self._hash = None self._status = StorageItemStatus.UNKNOWN", "str): # super(Directory, self).__init__(path) # # def is_dir(self): # return True class File(StorageItem):", "# represents items that used by Storage; # can be either a directory", "h.update(os.path.abspath(self._path)) digest = h.digest() digest_str = '' for b in digest: digest_str +=", "= '' for b in digest: digest_str += f'{b:02x}' self._hash = digest_str #", "= memoryview(b) with open(self._path, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv),", "media file, or non-media file import abc import hashlib import os import uuid", "import uuid from enum import Enum class StorageItemStatus(Enum): UNKNOWN = 'Unknown' ON_TARGET =", "path: str, uuid_str: str = None): super(File, self).__init__(path, uuid_str) def is_dir(self): return False", "'On Target' UPLOADING = 'Uploading' UPLOAD_FAILED = 'Upload Failed' UPLOADED = 'Uploaded' class", "# can be either a directory or media file, or non-media file import", "StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str = None): self._uuid = uuid_str if", "class StorageItem(abc.ABC): def __init__(self, path: str, uuid_str: str = None): self._uuid = uuid_str", "with open(self._path, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n])" ]
[ "expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted", "hashlib import pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE =", "and extracts an AES key, an HMAC key and an AES initialization vector.", "i in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] # Running the AES-128", "ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt", "'__main__': key = 'master key' message = 'a secret message' ciphertext = encrypt(key,", "aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE]", "\"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key,", "module docstring. \"\"\" if isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext, str): plaintext", "assert len(ciphertext) >= 32, \"\"\" Ciphertext must be at least 32 bytes long", "+ ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key` using AES-128,", "if __name__ == '__main__': key = 'master key' message = 'a secret message'", "the module docstring. \"\"\" if isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext, str):", "[encrypt, decrypt, AES] # Running the AES-128 if __name__ == '__main__': key =", "compare_digest from hashlib import pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16", "stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return", "== 0, \"Ciphertext must be made of full 16-byte blocks.\" assert len(ciphertext) >=", "workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched", "* 16 aes = AES(key) for i in range(30000): aes.encrypt_block(message) __all__ = [encrypt,", "\"\"\" Stretches the password and extracts an AES key, an HMAC key and", "is specified in the module docstring. \"\"\" assert len( ciphertext) % 16 ==", "get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password and extracts an AES key, an", "32 bytes long (16 byte salt + 16 byte block). To encrypt or", "`plaintext` with `key` using AES-128, an HMAC to verify integrity, and PBKDF2 to", "\"\"\" Ciphertext must be at least 32 bytes long (16 byte salt +", "be at least 32 bytes long (16 byte salt + 16 byte block).", "PBKDF2 to stretch the given key. The exact algorithm is specified in the", "assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark():", "given key. The exact algorithm is specified in the module docstring. \"\"\" assert", "exact algorithm is specified in the module docstring. \"\"\" if isinstance(key, str): key", "= get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt +", "hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac", "ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac + salt + ciphertext def", "'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P' *", "blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext =", "HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password and extracts", "an AES key, an HMAC key and an AES initialization vector. \"\"\" stretched", "len( ciphertext) % 16 == 0, \"Ciphertext must be made of full 16-byte", "and PBKDF2 to stretch the given key. The exact algorithm is specified in", "exact algorithm is specified in the module docstring. \"\"\" assert len( ciphertext) %", "iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts", "aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] # Running the AES-128 if __name__ ==", "ciphertext) % 16 == 0, \"Ciphertext must be made of full 16-byte blocks.\"", "get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt + ciphertext,", "str): key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE],", "workload=100000): \"\"\" Stretches the password and extracts an AES key, an HMAC key", "HMAC key and an AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt,", "plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt, workload)", "AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE", "= key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key,", "algorithm is specified in the module docstring. \"\"\" if isinstance(key, str): key =", "import AES from hmac import new as new_hmac, compare_digest from hashlib import pbkdf2_hmac", "or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P' * 16 message", "\"\"\" if isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt,", "__all__ = [encrypt, decrypt, AES] # Running the AES-128 if __name__ == '__main__':", "an HMAC to verify integrity, and PBKDF2 to stretch the given key. The", "= AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac) ==", "salt, workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac),", "salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac", "tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P' * 16 message =", "return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P' * 16 message = b'M'", "stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000):", "ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac)", "encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext = decrypt(key, ciphertext) print(\"Plaintext : {}\".format(str(plaintext,", "in the module docstring. \"\"\" if isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext,", "key = key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key,", "= key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key,", "iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key` using AES-128, an", "aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key` using", "hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key` using AES-128,", "decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key` using AES-128, an HMAC to", "from hashlib import pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE", "= 16 HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password", "isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt =", "hmac_key, iv = get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key,", "workload=100000): \"\"\" Decrypts `ciphertext` with `key` using AES-128, an HMAC to verify integrity,", "AES-128, an HMAC to verify integrity, and PBKDF2 to stretch the given key.", "key = 'master key' message = 'a secret message' ciphertext = encrypt(key, message)", "+ ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac + salt + ciphertext", "benchmark(): key = b'P' * 16 message = b'M' * 16 aes =", "module docstring. \"\"\" assert len( ciphertext) % 16 == 0, \"Ciphertext must be", "new_hmac, compare_digest from hashlib import pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE =", "extracts an AES key, an HMAC key and an AES initialization vector. \"\"\"", "blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext must be at least 32 bytes", "plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt, workload) ciphertext =", "ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key` using AES-128, an HMAC to verify", "ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv =", "decrypt, AES] # Running the AES-128 if __name__ == '__main__': key = 'master", "hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv def", "hmac import new as new_hmac, compare_digest from hashlib import pbkdf2_hmac import os AES_KEY_SIZE", "= ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key,", "AES key, an HMAC key and an AES initialization vector. \"\"\" stretched =", "password and extracts an AES key, an HMAC key and an AES initialization", "new as new_hmac, compare_digest from hashlib import pbkdf2_hmac import os AES_KEY_SIZE = 16", "AES-128 if __name__ == '__main__': key = 'master key' message = 'a secret", "To encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key", "stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key,", "specified in the module docstring. \"\"\" if isinstance(key, str): key = key.encode('utf-8') if", "with `key` using AES-128, an HMAC to verify integrity, and PBKDF2 to stretch", "HMAC_SIZE return hmac + salt + ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts", "= os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv)", "in the module docstring. \"\"\" assert len( ciphertext) % 16 == 0, \"Ciphertext", "salt = os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext,", "def benchmark(): key = b'P' * 16 message = b'M' * 16 aes", "\"\"\" Encrypts `plaintext` with `key` using AES-128, an HMAC to verify integrity, and", "message = b'M' * 16 aes = AES(key) for i in range(30000): aes.encrypt_block(message)", "full 16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext must be at least", "be made of full 16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext must", "= b'M' * 16 aes = AES(key) for i in range(30000): aes.encrypt_block(message) __all__", "docstring. \"\"\" if isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext, str): plaintext =", "for i in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] # Running the", "len(ciphertext) >= 32, \"\"\" Ciphertext must be at least 32 bytes long (16", "least 32 bytes long (16 byte salt + 16 byte block). To encrypt", "hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest()", "and an AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE", "iv = get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert", "(16 byte salt + 16 byte block). To encrypt or decrypt single blocks", "+ HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv", "hmac + salt + ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with", "str): key = key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE)", "isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key,", "return hmac + salt + ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext`", "if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv =", "= AES(key) for i in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] #", "= ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key,", "salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest()", "an AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE +", "initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE +", "as new_hmac, compare_digest from hashlib import pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE", "from aes import AES from hmac import new as new_hmac, compare_digest from hashlib", "message = 'a secret message' ciphertext = encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext))", "import pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE = 16", "get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest( hmac,", "message' ciphertext = encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext = decrypt(key, ciphertext)", "The exact algorithm is specified in the module docstring. \"\"\" assert len( ciphertext)", "= b'P' * 16 message = b'M' * 16 aes = AES(key) for", "= 'a secret message' ciphertext = encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext", "the AES-128 if __name__ == '__main__': key = 'master key' message = 'a", "Decrypts `ciphertext` with `key` using AES-128, an HMAC to verify integrity, and PBKDF2", "password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:]", "AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P' * 16 message = b'M' *", "+ salt + ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key`", "= 16 IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE = 32 def get_key_iv(password,", "must be made of full 16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext", "corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P' * 16", "os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE = 16", "16 == 0, \"Ciphertext must be made of full 16-byte blocks.\" assert len(ciphertext)", "key. The exact algorithm is specified in the module docstring. \"\"\" assert len(", "len(hmac) == HMAC_SIZE return hmac + salt + ciphertext def decrypt(key, ciphertext, workload=100000):", "AES(key) for i in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] # Running", "key, an HMAC key and an AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256',", "given key. The exact algorithm is specified in the module docstring. \"\"\" if", "to stretch the given key. The exact algorithm is specified in the module", "= stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext`", "isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext =", "'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def", "AES from hmac import new as new_hmac, compare_digest from hashlib import pbkdf2_hmac import", "stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\"", "integrity, and PBKDF2 to stretch the given key. The exact algorithm is specified", ">= 32, \"\"\" Ciphertext must be at least 32 bytes long (16 byte", "import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE =", "to verify integrity, and PBKDF2 to stretch the given key. The exact algorithm", "stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched", "def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key` using AES-128, an HMAC", "ciphertext = encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext = decrypt(key, ciphertext) print(\"Plaintext", "encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key` using AES-128, an HMAC to", "ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv)", "% 16 == 0, \"Ciphertext must be made of full 16-byte blocks.\" assert", "key = b'P' * 16 message = b'M' * 16 aes = AES(key)", "16 HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password and", "`ciphertext` with `key` using AES-128, an HMAC to verify integrity, and PBKDF2 to", "ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt, workload)", "use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE],", "stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key,", "key and an AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload,", "AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE", "'a secret message' ciphertext = encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext =", "16 SALT_SIZE = 16 HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches", "is specified in the module docstring. \"\"\" if isinstance(key, str): key = key.encode('utf-8')", "salt + ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key` using", "ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt +", "key. The exact algorithm is specified in the module docstring. \"\"\" if isinstance(key,", "from hmac import new as new_hmac, compare_digest from hashlib import pbkdf2_hmac import os", "+ 16 byte block). To encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\"", "Running the AES-128 if __name__ == '__main__': key = 'master key' message =", "HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv =", "the given key. The exact algorithm is specified in the module docstring. \"\"\"", "32, \"\"\" Ciphertext must be at least 32 bytes long (16 byte salt", "IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000):", "workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext", "byte salt + 16 byte block). To encrypt or decrypt single blocks use", "salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key,", "must be at least 32 bytes long (16 byte salt + 16 byte", "long (16 byte salt + 16 byte block). To encrypt or decrypt single", "salt + ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac + salt +", "b'P' * 16 message = b'M' * 16 aes = AES(key) for i", "return aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key`", "16 aes = AES(key) for i in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt,", "== '__main__': key = 'master key' message = 'a secret message' ciphertext =", "key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:]", "def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password and extracts an AES key,", "assert len( ciphertext) % 16 == 0, \"Ciphertext must be made of full", "+ ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext,", "encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key =", "key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv", "16 byte block). To encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if", "Encrypts `plaintext` with `key` using AES-128, an HMAC to verify integrity, and PBKDF2", "key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key,", "= get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest(", "== HMAC_SIZE return hmac + salt + ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\"", "\"\"\" Decrypts `ciphertext` with `key` using AES-128, an HMAC to verify integrity, and", "= 16 SALT_SIZE = 16 HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000): \"\"\"", "workload=100000): \"\"\" Encrypts `plaintext` with `key` using AES-128, an HMAC to verify integrity,", "byte block). To encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key,", "`AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:]", "stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv", "* 16 message = b'M' * 16 aes = AES(key) for i in", "# Running the AES-128 if __name__ == '__main__': key = 'master key' message", "using AES-128, an HMAC to verify integrity, and PBKDF2 to stretch the given", "ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt,", "The exact algorithm is specified in the module docstring. \"\"\" if isinstance(key, str):", "stretch the given key. The exact algorithm is specified in the module docstring.", "= [encrypt, decrypt, AES] # Running the AES-128 if __name__ == '__main__': key", "import new as new_hmac, compare_digest from hashlib import pbkdf2_hmac import os AES_KEY_SIZE =", "salt + 16 byte block). To encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`.", "plaintext, workload=100000): \"\"\" Encrypts `plaintext` with `key` using AES-128, an HMAC to verify", "vector. \"\"\" stretched = pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE)", "= encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext = decrypt(key, ciphertext) print(\"Plaintext :", "if isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext", "new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac + salt", "= plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt, workload) ciphertext", "32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password and extracts an AES", "'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac + salt + ciphertext def decrypt(key,", "algorithm is specified in the module docstring. \"\"\" assert len( ciphertext) % 16", "= 16 HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE =", "new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.'", "docstring. \"\"\" assert len( ciphertext) % 16 == 0, \"Ciphertext must be made", "bytes long (16 byte salt + 16 byte block). To encrypt or decrypt", "or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key = key.encode('utf-8')", "AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched =", "made of full 16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext must be", "iv) def benchmark(): key = b'P' * 16 message = b'M' * 16", "str): plaintext = plaintext.encode('utf-8') salt = os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt,", "iv = get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt", "hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key =", "aes import AES from hmac import new as new_hmac, compare_digest from hashlib import", "\"Ciphertext must be made of full 16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\"", "\"\"\" if isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8')", "os.urandom(SALT_SIZE) key, hmac_key, iv = get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac", "16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext must be at least 32", "16 message = b'M' * 16 aes = AES(key) for i in range(30000):", "secret message' ciphertext = encrypt(key, message) print(\"Cipher text : {}\".format(ciphertext)) plaintext = decrypt(key,", "key, hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac = new_hmac(hmac_key, salt + ciphertext,", "verify integrity, and PBKDF2 to stretch the given key. The exact algorithm is", "of full 16-byte blocks.\" assert len(ciphertext) >= 32, \"\"\" Ciphertext must be at", "__name__ == '__main__': key = 'master key' message = 'a secret message' ciphertext", "ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv = get_key_iv(key, salt, workload) expected_hmac =", "= stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key,", "= new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or", "'master key' message = 'a secret message' ciphertext = encrypt(key, message) print(\"Cipher text", "compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key", "Ciphertext must be at least 32 bytes long (16 byte salt + 16", "key' message = 'a secret message' ciphertext = encrypt(key, message) print(\"Cipher text :", "b'M' * 16 aes = AES(key) for i in range(30000): aes.encrypt_block(message) __all__ =", "key, hmac_key, iv = get_key_iv(key, salt, workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac =", "specified in the module docstring. \"\"\" assert len( ciphertext) % 16 == 0,", "IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:]", "assert len(hmac) == HMAC_SIZE return hmac + salt + ciphertext def decrypt(key, ciphertext,", "salt, workload=100000): \"\"\" Stretches the password and extracts an AES key, an HMAC", "+ IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE], stretched[AES_KEY_SIZE:] hmac_key, stretched = stretched[:HMAC_KEY_SIZE],", "stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key, plaintext, workload=100000): \"\"\" Encrypts `plaintext` with", "decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key = key.encode('utf-8') hmac,", "= new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return hmac +", "block). To encrypt or decrypt single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str):", "= 'master key' message = 'a secret message' ciphertext = encrypt(key, message) print(\"Cipher", "salt + ciphertext, 'sha256').digest() assert compare_digest( hmac, expected_hmac), 'Ciphertext corrupted or tampered.' return", "in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] # Running the AES-128 if", "pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched = stretched[:AES_KEY_SIZE],", "ciphertext def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key` using AES-128, an", "hmac, ciphertext = ciphertext[:HMAC_SIZE], ciphertext[HMAC_SIZE:] salt, ciphertext = ciphertext[:SALT_SIZE], ciphertext[SALT_SIZE:] key, hmac_key, iv", "16 IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE = 32 def get_key_iv(password, salt,", "at least 32 bytes long (16 byte salt + 16 byte block). To", "if isinstance(key, str): key = key.encode('utf-8') if isinstance(plaintext, str): plaintext = plaintext.encode('utf-8') salt", "aes = AES(key) for i in range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES]", "= 32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the password and extracts an", "iv) hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert len(hmac) == HMAC_SIZE return", "= pbkdf2_hmac('sha256', password, salt, workload, AES_KEY_SIZE + IV_SIZE + HMAC_KEY_SIZE) aes_key, stretched =", "AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE", "an HMAC key and an AES initialization vector. \"\"\" stretched = pbkdf2_hmac('sha256', password,", "0, \"Ciphertext must be made of full 16-byte blocks.\" assert len(ciphertext) >= 32,", "range(30000): aes.encrypt_block(message) __all__ = [encrypt, decrypt, AES] # Running the AES-128 if __name__", "message) print(\"Cipher text : {}\".format(ciphertext)) plaintext = decrypt(key, ciphertext) print(\"Plaintext : {}\".format(str(plaintext, 'utf-8')))", "16 HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE = 32", "= stretched[:HMAC_KEY_SIZE], stretched[HMAC_KEY_SIZE:] iv = stretched[:IV_SIZE] return aes_key, hmac_key, iv def encrypt(key, plaintext,", "single blocks use `AES(key).decrypt_block(ciphertext)`. \"\"\" if isinstance(key, str): key = key.encode('utf-8') hmac, ciphertext", "expected_hmac), 'Ciphertext corrupted or tampered.' return AES(key).decrypt_cbc(ciphertext, iv) def benchmark(): key = b'P'", "the module docstring. \"\"\" assert len( ciphertext) % 16 == 0, \"Ciphertext must", "SALT_SIZE = 16 HMAC_SIZE = 32 def get_key_iv(password, salt, workload=100000): \"\"\" Stretches the", "workload) ciphertext = AES(key).encrypt_cbc(plaintext, iv) hmac = new_hmac(hmac_key, salt + ciphertext, 'sha256').digest() assert", "Stretches the password and extracts an AES key, an HMAC key and an", "HMAC to verify integrity, and PBKDF2 to stretch the given key. The exact", "def decrypt(key, ciphertext, workload=100000): \"\"\" Decrypts `ciphertext` with `key` using AES-128, an HMAC", "`key` using AES-128, an HMAC to verify integrity, and PBKDF2 to stretch the", "pbkdf2_hmac import os AES_KEY_SIZE = 16 HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE", "the password and extracts an AES key, an HMAC key and an AES", "\"\"\" assert len( ciphertext) % 16 == 0, \"Ciphertext must be made of", "HMAC_KEY_SIZE = 16 IV_SIZE = 16 SALT_SIZE = 16 HMAC_SIZE = 32 def", "AES] # Running the AES-128 if __name__ == '__main__': key = 'master key'" ]
[]
[ "self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete()", "= User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete()", "import Image,Profile from django.contrib.auth.models import User # Create your tests here. class ProfileTestCase(TestCase):", "#creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self):", "Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self):", "new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\")", "Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save()", "#creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\")", "def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image", "from django.contrib.auth.models import User # Create your tests here. class ProfileTestCase(TestCase): # SetUp", "self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.delete() images = Image.objects.all() self.assertTrue(len(images)==0)", "test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images = Image.objects.all()", "= User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def setUp(self): #creating a user", "def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): #", "from django.test import TestCase from .models import Image,Profile from django.contrib.auth.models import User #", "User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def setUp(self):", "= Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.delete() images =", "= User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() #", "Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all()", "Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users =", "def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def", "Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save()", "import TestCase from .models import Image,Profile from django.contrib.auth.models import User # Create your", "# Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users", "def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1)", "new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def setUp(self): #creating", "your tests here. class ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating a user", "from .models import Image,Profile from django.contrib.auth.models import User # Create your tests here.", "# Create your tests here. class ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating", "setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def", "User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def", "setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its", "user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete()", "at its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at", "self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance self.user", "def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user", "test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self):", "import User # Create your tests here. class ProfileTestCase(TestCase): # SetUp method def", "# SetUp method def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image", "= User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance", "User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class", "users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all()", "= Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image))", "Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self):", "user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self):", "def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images =", "a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def", "class ImageTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance self.user =", "method def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce", "self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self):", "TestCase from .models import Image,Profile from django.contrib.auth.models import User # Create your tests", "tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user =", "at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image))", "User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance", "new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method", "self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance", "Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images", "User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\")", ".models import Image,Profile from django.contrib.auth.models import User # Create your tests here. class", "test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp", "User # Create your tests here. class ProfileTestCase(TestCase): # SetUp method def setUp(self):", "self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self):", "self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing", "= User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0)", "self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1)", "instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() #", "Create your tests here. class ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating a", "class ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance self.user =", "new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.delete()", "django.test import TestCase from .models import Image,Profile from django.contrib.auth.models import User # Create", "User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at", "its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its", "self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase):", "= User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def", "django.contrib.auth.models import User # Create your tests here. class ProfileTestCase(TestCase): # SetUp method", "best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\")", "Image,Profile from django.contrib.auth.models import User # Create your tests here. class ProfileTestCase(TestCase): #", "best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self):", "test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user =", "Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def", "# Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\")", "tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai", "here. class ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance self.user", "users = User.objects.all() self.assertTrue(len(users)<=0) class ImageTestCase(TestCase): # SetUp method def setUp(self): #creating a", "Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_image(self): new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its", "new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users =", "new_image =Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image", "def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at", "SetUp method def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image =", "=Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.save() images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai", "def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\")", "its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def", "ImageTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\")", "User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing", "method def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai", "test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def", "def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def test_instance(self): self.assertTrue(isinstance(self.image,Image)) def test_save_profile(self): new_user", "ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\")", "a user instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Profile(user=self.user,profile_avatar=\"ben_H62Kawu.jpeg\",bio=\"Rolls-Royce Wraith\") def tearDown(self): User.objects.all().delete()", "images = Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.delete() images", "User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.save() users = User.objects.all() self.assertTrue(len(users)>=1) def test_delete_profile(self): new_user = User(id=1,username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") new_user.delete() users", "instance self.user = User(username=\"chris\",email=\"<EMAIL>\",password=\"<PASSWORD>\") self.image = Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete()", "= Image(image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") def tearDown(self): User.objects.all().delete() Image.objects.all().delete() # Testing Instance def", "Image.objects.all() self.assertTrue(len(images)>=1) def test_delete_image(self): new_image =Image(id=1,image=\"default.jpg\",tag_someone=\"ben2_2HRlWyC.jpeg\",image_caption=\"ai at its best\") new_image.delete() images = Image.objects.all()", "tests here. class ProfileTestCase(TestCase): # SetUp method def setUp(self): #creating a user instance" ]
[ "test_run_script(): # run 1 # run 2 # assert assert 1 == 1", "pytest def test_run_script(): # run 1 # run 2 # assert assert 1", "def test_run_script(): # run 1 # run 2 # assert assert 1 ==", "import pytest def test_run_script(): # run 1 # run 2 # assert assert" ]
[ "get_context(): try: return geni.util.loadContext() except IOError as e: # File not found. No", "= ~/.ssh/cloudlab.pem (Cert must not be protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub", "No credentials loaded? print('ERROR: Could not load context: ', e) print('''Are there any", "by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.) <name> = skyhook", "If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context --type cloudlab --cert", "<cert> --pubkey <pubkey> --project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not", "--cert <cert> --pubkey <pubkey> --project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must", "a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.) <name> = skyhook (Note:", "without a password.) <name> = skyhook (Note: must be all lowercase!) ''') return", "(Cert must not be protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without", "', e) print('''Are there any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for", "<pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.) <name> = skyhook (Note: must be", "import geni.util def get_context(): try: return geni.util.loadContext() except IOError as e: # File", "found. No credentials loaded? print('ERROR: Could not load context: ', e) print('''Are there", "any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context", "Could not load context: ', e) print('''Are there any credentials available? If not,", "cloudlab --cert <cert> --pubkey <pubkey> --project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert", "--type cloudlab --cert <cert> --pubkey <pubkey> --project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem", "there any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use:", "--project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not be protected by", "context: ', e) print('''Are there any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically,", "With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not be protected by a password!)", "geni.util def get_context(): try: return geni.util.loadContext() except IOError as e: # File not", "<cert> = ~/.ssh/cloudlab.pem (Cert must not be protected by a password!) <pubkey> =", "protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.) <name> =", "~/.ssh/geni.rsa.pub (Preferably without a password.) <name> = skyhook (Note: must be all lowercase!)", "check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context --type cloudlab --cert <cert> --pubkey", "use: build-context --type cloudlab --cert <cert> --pubkey <pubkey> --project <name> With e.g: <cert>", "except IOError as e: # File not found. No credentials loaded? print('ERROR: Could", "e) print('''Are there any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab", "password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.) <name> = skyhook (Note: must", "(Preferably without a password.) <name> = skyhook (Note: must be all lowercase!) ''')", "available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context --type cloudlab", "--pubkey <pubkey> --project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not be", "IOError as e: # File not found. No credentials loaded? print('ERROR: Could not", "<name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not be protected by a", "# File not found. No credentials loaded? print('ERROR: Could not load context: ',", "File not found. No credentials loaded? print('ERROR: Could not load context: ', e)", "https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context --type cloudlab --cert <cert> --pubkey <pubkey>", "not found. No credentials loaded? print('ERROR: Could not load context: ', e) print('''Are", "cloudlab users, use: build-context --type cloudlab --cert <cert> --pubkey <pubkey> --project <name> With", "<pubkey> --project <name> With e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not be protected", "e: # File not found. No credentials loaded? print('ERROR: Could not load context:", "be protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.) <name>", "return geni.util.loadContext() except IOError as e: # File not found. No credentials loaded?", "credentials loaded? print('ERROR: Could not load context: ', e) print('''Are there any credentials", "as e: # File not found. No credentials loaded? print('ERROR: Could not load", "not load context: ', e) print('''Are there any credentials available? If not, check", "print('''Are there any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users,", "credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context --type", "print('ERROR: Could not load context: ', e) print('''Are there any credentials available? If", "for cloudlab users, use: build-context --type cloudlab --cert <cert> --pubkey <pubkey> --project <name>", "not be protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a password.)", "e.g: <cert> = ~/.ssh/cloudlab.pem (Cert must not be protected by a password!) <pubkey>", "= ~/.ssh/geni.rsa.pub (Preferably without a password.) <name> = skyhook (Note: must be all", "loaded? print('ERROR: Could not load context: ', e) print('''Are there any credentials available?", "must not be protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably without a", "users, use: build-context --type cloudlab --cert <cert> --pubkey <pubkey> --project <name> With e.g:", "load context: ', e) print('''Are there any credentials available? If not, check https://docs.emulab.net/geni-lib/intro/credentials.html", "Specifically, for cloudlab users, use: build-context --type cloudlab --cert <cert> --pubkey <pubkey> --project", "def get_context(): try: return geni.util.loadContext() except IOError as e: # File not found.", "build-context --type cloudlab --cert <cert> --pubkey <pubkey> --project <name> With e.g: <cert> =", "~/.ssh/cloudlab.pem (Cert must not be protected by a password!) <pubkey> = ~/.ssh/geni.rsa.pub (Preferably", "try: return geni.util.loadContext() except IOError as e: # File not found. No credentials", "not, check https://docs.emulab.net/geni-lib/intro/credentials.html Specifically, for cloudlab users, use: build-context --type cloudlab --cert <cert>", "geni.util.loadContext() except IOError as e: # File not found. No credentials loaded? print('ERROR:", "a password.) <name> = skyhook (Note: must be all lowercase!) ''') return None" ]
[ "from click import progressbar import numpy as np def read_skeleton_file(file_path: str): with open(file_path,", "f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in", "joints: data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def", "for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for _ in", "joint_number, joint in enumerate(body['jointInfo']): if body_number < persons and joint_number < joints: data[:,", "body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if body_number < persons", "def generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\")", "float(v) for k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] =", "= progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\")", "body_info = { k: float(v) for k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint']", "25, persons = 2) -> None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'],", "frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key = [", "sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body in", "float(v) for k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence", "'orientationZ', 'trackingState' ] joint_info = { k: float(v) for k, v in zip(joint_info_key,", "= [ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ',", "progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data =", "{ k: float(v) for k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline())", "persons = 2) -> None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints,", "in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\",", "return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int = 25, persons = 2) ->", "in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if", "int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence',", "int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []}", "os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\") f.write(sequence_name) f.write(\"\\r\\n\") f.close()", "joint in enumerate(body['jointInfo']): if body_number < persons and joint_number < joints: data[:, frame_number,", "f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info =", "f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for _ in range(body_info['numJoint']): joint_info_key", "joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path:", "'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info = { k: float(v)", "for _ in range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX',", "for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint", "'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info = { k:", "= parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\") f.write(sequence_name) f.write(\"\\r\\n\") f.close() target_file.create_group(sequence_name).create_dataset(\"skeleton\", data=skeleton_data)", "= [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ]", "int(f.readline()) body_info['jointInfo'] = [] for _ in range(body_info['numJoint']): joint_info_key = [ 'x', 'y',", "body_number < persons and joint_number < joints: data[:, frame_number, joint_number, body_number] = [joint['x'],", "in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key", "progressbar import numpy as np def read_skeleton_file(file_path: str): with open(file_path, 'r') as f:", "'trackingState' ] joint_info = { k: float(v) for k, v in zip(joint_info_key, f.readline().split())", "body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str)", "'leanY', 'trackingState' ] body_info = { k: float(v) for k, v in zip(body_info_key,", "sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\") f.write(sequence_name)", "import h5py from click import progressbar import numpy as np def read_skeleton_file(file_path: str):", "_ in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted',", "body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int = 25, persons", "-> None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for", "persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for", "in enumerate(body['jointInfo']): if body_number < persons and joint_number < joints: data[:, frame_number, joint_number,", "if body_number < persons and joint_number < joints: data[:, frame_number, joint_number, body_number] =", "data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path:", "{'numBody': int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges',", "in range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW',", "[joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) -> None:", "= read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame in", "data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for", "import numpy as np def read_skeleton_file(file_path: str): with open(file_path, 'r') as f: skeleton_sequence", "persons and joint_number < joints: data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']]", "[]} for _ in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence',", "\"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name =", "joints, persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']):", "for k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def", "[]} for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for _", "sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame", "'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState',", "k: float(v) for k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return", "parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\") f.write(sequence_name) f.write(\"\\r\\n\") f.close() target_file.create_group(sequence_name).create_dataset(\"skeleton\", data=skeleton_data) progress_bar.update(1)", "def parse_skeleton_data(file_path: str, joints: int = 25, persons = 2) -> None: sequence_data", "'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info = { k: float(v) for k, v", "range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key =", "import os import h5py from click import progressbar import numpy as np def", "= [] for _ in range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z', 'depthX',", "in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX',", "'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info = { k:", "generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as", "'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info = { k: float(v) for", "numpy as np def read_skeleton_file(file_path: str): with open(file_path, 'r') as f: skeleton_sequence =", "[] for _ in range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z', 'depthX', 'depthY',", "os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\")", "'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info = { k: float(v) for k, v", "joint_info = { k: float(v) for k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info)", "in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if body_number < persons and joint_number", "and joint_number < joints: data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return", "for _ in range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState',", "skeleton_sequence def parse_skeleton_data(file_path: str, joints: int = 25, persons = 2) -> None:", "< persons and joint_number < joints: data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'],", "[ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info", "'trackingState' ] body_info = { k: float(v) for k, v in zip(body_info_key, f.readline().split())", "'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info = { k: float(v) for k,", "joint_info_key = [ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY',", "= {'numFrame': int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()),", "np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with", "frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint in", "file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path +", "in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for _ in", "[ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState'", "as np def read_skeleton_file(file_path: str): with open(file_path, 'r') as f: skeleton_sequence = {'numFrame':", "= { k: float(v) for k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info)", "open(file_path, 'r') as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for _ in", "os import h5py from click import progressbar import numpy as np def read_skeleton_file(file_path:", "body in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if body_number < persons and", "import progressbar import numpy as np def read_skeleton_file(file_path: str): with open(file_path, 'r') as", "<reponame>kanmaytacker/heart-net import os import h5py from click import progressbar import numpy as np", "{'numFrame': int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo':", "progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f", "frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int = 25, persons =", "-> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None,", "'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info = {", "} body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int = 25,", "h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name", "as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info", "= 2) -> None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons),", "skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody':", "v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for _", "str, output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file:", "= int(f.readline()) body_info['jointInfo'] = [] for _ in range(body_info['numJoint']): joint_info_key = [ 'x',", "int = 25, persons = 2) -> None: sequence_data = read_skeleton_file(file_path) data =", "k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for", "joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path =", "= os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\") f.write(sequence_name) f.write(\"\\r\\n\")", "for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path", "'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info = { k: float(v)", "'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info = { k: float(v) for", "joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path", "] body_info = { k: float(v) for k, v in zip(body_info_key, f.readline().split()) }", "f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int =", "] joint_info = { k: float(v) for k, v in zip(joint_info_key, f.readline().split()) }", "np def read_skeleton_file(file_path: str): with open(file_path, 'r') as f: skeleton_sequence = {'numFrame': int(f.readline()),", "for body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if body_number <", "target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for", "return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\"", "as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0]", "enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if body_number < persons and joint_number <", "decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path,", "= f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name", "= { k: float(v) for k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] =", "target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data", "{ k: float(v) for k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info)", "range(frame_info['numBody']): body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY',", "str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar =", "'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info = { k: float(v) for k,", "'r') as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for _ in range(skeleton_sequence['numFrame']):", "< joints: data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3)", "with h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path):", "length=len(next(os.walk(data_path))[2])) for file_name in os.listdir(data_path): sequence_name = os.path.splitext(file_name)[0] skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f =", "} body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for _ in range(body_info['numJoint']): joint_info_key =", "zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int", "parse_skeleton_data(file_path: str, joints: int = 25, persons = 2) -> None: sequence_data =", "_ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']):", "zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for _ in range(body_info['numJoint']):", "range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX',", "'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info =", "= np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number,", "with open(file_path, 'r') as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for _", "'orientationY', 'orientationZ', 'trackingState' ] joint_info = { k: float(v) for k, v in", "None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number,", "body_info_key = [ 'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState'", "body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = [] for _ in range(body_info['numJoint']): joint_info_key = [", "for k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo'] = []", "'leanX', 'leanY', 'trackingState' ] body_info = { k: float(v) for k, v in", "_ in range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY',", "= [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str, output_path: str) ->", "'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ] joint_info", "read_skeleton_file(file_path: str): with open(file_path, 'r') as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []}", "enumerate(body['jointInfo']): if body_number < persons and joint_number < joints: data[:, frame_number, joint_number, body_number]", "'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info = {", "k, v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path:", "joint_number < joints: data[:, frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data,", "= {'numBody': int(f.readline()), 'bodyInfo': []} for _ in range(frame_info['numBody']): body_info_key = [ 'bodyID',", "'bodyID', 'clippedEdges', 'handLeftConfidence', 'handLeftState', 'handRightConfidence', 'handRightState', 'isResticted', 'leanX', 'leanY', 'trackingState' ] body_info =", "str, joints: int = 25, persons = 2) -> None: sequence_data = read_skeleton_file(file_path)", "'frameInfo': []} for _ in range(skeleton_sequence['numFrame']): frame_info = {'numBody': int(f.readline()), 'bodyInfo': []} for", "= 25, persons = 2) -> None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3,", "in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints:", "skeleton_data = parse_skeleton_data(f\"{data_path}/{file_name}\") f = open(output_path + \"log.txt\", \"w+\") f.write(sequence_name) f.write(\"\\r\\n\") f.close() target_file.create_group(sequence_name).create_dataset(\"skeleton\",", "k: float(v) for k, v in zip(body_info_key, f.readline().split()) } body_info['numJoint'] = int(f.readline()) body_info['jointInfo']", "np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body", "output_path: str) -> None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar", "def read_skeleton_file(file_path: str): with open(file_path, 'r') as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo':", "frame in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']):", "body_info['jointInfo'] = [] for _ in range(body_info['numJoint']): joint_info_key = [ 'x', 'y', 'z',", "2) -> None: sequence_data = read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32)", "skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str, joints: int = 25, persons = 2)", "frame_number, joint_number, body_number] = [joint['x'], joint['y'], joint['z']] return np.around(data, decimals=3) def generate_skeleton_dataset(data_path: str,", "joints: int = 25, persons = 2) -> None: sequence_data = read_skeleton_file(file_path) data", "enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for joint_number, joint in enumerate(body['jointInfo']): if body_number", "str): with open(file_path, 'r') as f: skeleton_sequence = {'numFrame': int(f.readline()), 'frameInfo': []} for", "'x', 'y', 'z', 'depthX', 'depthY', 'colorX', 'colorY', 'orientationW', 'orientationX', 'orientationY', 'orientationZ', 'trackingState' ]", "dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']): for body_number, body in enumerate(frame['bodyInfo']): for joint_number,", "for joint_number, joint in enumerate(body['jointInfo']): if body_number < persons and joint_number < joints:", "h5py from click import progressbar import numpy as np def read_skeleton_file(file_path: str): with", "read_skeleton_file(file_path) data = np.zeros((3, sequence_data['numFrame'], joints, persons), dtype=np.float32) for frame_number, frame in enumerate(sequence_data['frameInfo']):", "click import progressbar import numpy as np def read_skeleton_file(file_path: str): with open(file_path, 'r')", "None: target_file_path = f\"{output_path}/skeleton.h5\" with h5py.File(target_file_path, \"w\") as target_file: progress_bar = progressbar(iterable=None, length=len(next(os.walk(data_path))[2]))", "v in zip(joint_info_key, f.readline().split()) } body_info['jointInfo'].append(joint_info) frame_info['bodyInfo'].append(body_info) skeleton_sequence['frameInfo'].append(frame_info) return skeleton_sequence def parse_skeleton_data(file_path: str," ]
[ "specific vegetation types ''' Headers, A = LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID']", "A = LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] == 2)]['ID']", "< Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return Small, Large def VegDataFilter(DataFile): '''", "as np def LoadData(FileName): ''' Loads hollow data into structured numpy array of", "array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): '''", "''' Split hollows around Value of a given property. returns Small and Large,", "the data into separate structured arrays by aspect band and returns a tuple", "Headers, A = LoadData(FileName) NE = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)]", "to hollows above and below the median. ''' Headers, A = LoadData(DataFile) Small", "return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow data into structured numpy array", "into structured numpy array of floats and returns a tuple of column headers", "A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)] E = A[(A['Aspect'] >= 0) &", "<= 165)] W = A[(A['Aspect'] > 165)] return Headers, NE, SE, E, W", "Small and Large, two lists of IDs corresponding to hollows above and below", "''' Headers, A = LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter]", "Value)]['ID'] return Small, Large def VegDataFilter(DataFile): ''' Split hollows into vegetation categories of", "165)] return Headers, NE, SE, E, W def DataFilter(DataFile, Parameter, Value): ''' Split", "corresponding to specific vegetation types ''' Headers, A = LoadData(DataFile) a = A[(A['Veg']", "with the structured array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data", "structured array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName):", "A[(A[Parameter] >= Value)]['ID'] return Small, Large def VegDataFilter(DataFile): ''' Split hollows into vegetation", "def VegDataFilter(DataFile): ''' Split hollows into vegetation categories of a given property. returns", "lists of IDs corresponding to specific vegetation types ''' Headers, A = LoadData(DataFile)", "of IDs corresponding to specific vegetation types ''' Headers, A = LoadData(DataFile) a", "returns 4 lists of IDs corresponding to specific vegetation types ''' Headers, A", "and returns a tuple of column headers along with the structured array. '''", "property. returns Small and Large, two lists of IDs corresponding to hollows above", "floats and returns a tuple of column headers along with the structured array.", "aspect band and returns a tuple of column headers along with the structured", "hollows around Value of a given property. returns Small and Large, two lists", "= A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] == 4)]['ID'] return a, b, c,", "= A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return Small, Large def", "Large def VegDataFilter(DataFile): ''' Split hollows into vegetation categories of a given property.", ">= 0) & (A['Aspect'] <= 85)] SE = A[(A['Aspect'] > 85) & (A['Aspect']", "A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)] SE = A[(A['Aspect'] > 85) &", "Loads hollow data into structured numpy array of floats and returns a tuple", "separate structured arrays by aspect band and returns a tuple of column headers", "tuple of column headers along with the structured arrays. ''' Headers, A =", "array of floats, and splits the data into separate structured arrays by aspect", "= A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)] E = A[(A['Aspect'] >= 0)", "0) & (A['Aspect'] <= 165)] W = A[(A['Aspect'] > 165)] return Headers, NE,", "SegmentDataByAspect(FileName): ''' Loads hollow data into structured numpy array of floats, and splits", "Value of a given property. returns Small and Large, two lists of IDs", "> 85) & (A['Aspect'] <= 165)] E = A[(A['Aspect'] >= 0) & (A['Aspect']", "Small = A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return Small, Large", "data into structured numpy array of floats and returns a tuple of column", "of a given property. returns 4 lists of IDs corresponding to specific vegetation", "around Value of a given property. returns Small and Large, two lists of", "A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)] W = A[(A['Aspect'] > 165)] return", "column headers along with the structured array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',')", "into vegetation categories of a given property. returns 4 lists of IDs corresponding", "into separate structured arrays by aspect band and returns a tuple of column", "data into structured numpy array of floats, and splits the data into separate", "& (A['Aspect'] <= 85)] SE = A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)]", "types ''' Headers, A = LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b =", "''' Loads hollow data into structured numpy array of floats, and splits the", "VegDataFilter(DataFile): ''' Split hollows into vegetation categories of a given property. returns 4", "of a given property. returns Small and Large, two lists of IDs corresponding", "lists of IDs corresponding to hollows above and below the median. ''' Headers,", "numpy as np def LoadData(FileName): ''' Loads hollow data into structured numpy array", "= A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] ==", "return Small, Large def VegDataFilter(DataFile): ''' Split hollows into vegetation categories of a", "structured numpy array of floats, and splits the data into separate structured arrays", "A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] == 4)]['ID']", "np def LoadData(FileName): ''' Loads hollow data into structured numpy array of floats", "1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d =", "85) & (A['Aspect'] <= 165)] E = A[(A['Aspect'] >= 0) & (A['Aspect'] <=", "array of floats and returns a tuple of column headers along with the", "a given property. returns Small and Large, two lists of IDs corresponding to", "SE, E, W def DataFilter(DataFile, Parameter, Value): ''' Split hollows around Value of", "along with the structured array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names,", "along with the structured arrays. ''' Headers, A = LoadData(FileName) NE = A[(A['Aspect']", "of IDs corresponding to hollows above and below the median. ''' Headers, A", "Small, Large def VegDataFilter(DataFile): ''' Split hollows into vegetation categories of a given", "data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow data into structured numpy array of", "Headers, A = LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >=", "<= 85)] SE = A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)] E =", "arrays. ''' Headers, A = LoadData(FileName) NE = A[(A['Aspect'] >= 0) & (A['Aspect']", "c = A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] == 4)]['ID'] return a, b,", "A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] == 4)]['ID'] return a, b, c, d", "A = LoadData(FileName) NE = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)] SE", "165)] E = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)] W = A[(A['Aspect']", "vegetation categories of a given property. returns 4 lists of IDs corresponding to", "given property. returns 4 lists of IDs corresponding to specific vegetation types '''", "a tuple of column headers along with the structured array. ''' data =", "(A['Aspect'] <= 85)] SE = A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)] E", "= A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)] SE = A[(A['Aspect'] > 85)", "returns Small and Large, two lists of IDs corresponding to hollows above and", "def LoadData(FileName): ''' Loads hollow data into structured numpy array of floats and", "return Headers, NE, SE, E, W def DataFilter(DataFile, Parameter, Value): ''' Split hollows", "(A['Aspect'] <= 165)] E = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)] W", "A[(A['Aspect'] > 165)] return Headers, NE, SE, E, W def DataFilter(DataFile, Parameter, Value):", "vegetation types ''' Headers, A = LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b", "delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow data into structured numpy", "a given property. returns 4 lists of IDs corresponding to specific vegetation types", "= A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] ==", "== 1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d", "with the structured arrays. ''' Headers, A = LoadData(FileName) NE = A[(A['Aspect'] >=", "W def DataFilter(DataFile, Parameter, Value): ''' Split hollows around Value of a given", "splits the data into separate structured arrays by aspect band and returns a", "column headers along with the structured arrays. ''' Headers, A = LoadData(FileName) NE", "165)] W = A[(A['Aspect'] > 165)] return Headers, NE, SE, E, W def", "IDs corresponding to hollows above and below the median. ''' Headers, A =", ">= 0) & (A['Aspect'] <= 165)] W = A[(A['Aspect'] > 165)] return Headers,", "of floats, and splits the data into separate structured arrays by aspect band", "> 165)] return Headers, NE, SE, E, W def DataFilter(DataFile, Parameter, Value): '''", "== 2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] == 4)]['ID'] return", ">= Value)]['ID'] return Small, Large def VegDataFilter(DataFile): ''' Split hollows into vegetation categories", "''' Headers, A = LoadData(FileName) NE = A[(A['Aspect'] >= 0) & (A['Aspect'] <=", "NE, SE, E, W def DataFilter(DataFile, Parameter, Value): ''' Split hollows around Value", "Loads hollow data into structured numpy array of floats, and splits the data", "(A['Aspect'] <= 165)] W = A[(A['Aspect'] > 165)] return Headers, NE, SE, E,", "= A[(A[Parameter] >= Value)]['ID'] return Small, Large def VegDataFilter(DataFile): ''' Split hollows into", "Headers, NE, SE, E, W def DataFilter(DataFile, Parameter, Value): ''' Split hollows around", "SE = A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)] E = A[(A['Aspect'] >=", "''' Split hollows into vegetation categories of a given property. returns 4 lists", "to specific vegetation types ''' Headers, A = LoadData(DataFile) a = A[(A['Veg'] ==", "85)] SE = A[(A['Aspect'] > 85) & (A['Aspect'] <= 165)] E = A[(A['Aspect']", "4 lists of IDs corresponding to specific vegetation types ''' Headers, A =", "= LoadData(FileName) NE = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)] SE =", "& (A['Aspect'] <= 165)] E = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)]", "def SegmentDataByAspect(FileName): ''' Loads hollow data into structured numpy array of floats, and", "numpy array of floats and returns a tuple of column headers along with", "property. returns 4 lists of IDs corresponding to specific vegetation types ''' Headers,", "a tuple of column headers along with the structured arrays. ''' Headers, A", "a = A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg']", "LoadData(FileName) NE = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)] SE = A[(A['Aspect']", "DataFilter(DataFile, Parameter, Value): ''' Split hollows around Value of a given property. returns", "hollows above and below the median. ''' Headers, A = LoadData(DataFile) Small =", "structured numpy array of floats and returns a tuple of column headers along", "corresponding to hollows above and below the median. ''' Headers, A = LoadData(DataFile)", "W = A[(A['Aspect'] > 165)] return Headers, NE, SE, E, W def DataFilter(DataFile,", "''' Headers, A = LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg']", "of floats and returns a tuple of column headers along with the structured", "& (A['Aspect'] <= 165)] W = A[(A['Aspect'] > 165)] return Headers, NE, SE,", "Large = A[(A[Parameter] >= Value)]['ID'] return Small, Large def VegDataFilter(DataFile): ''' Split hollows", "Split hollows around Value of a given property. returns Small and Large, two", "the median. ''' Headers, A = LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large", "= LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return", "data def SegmentDataByAspect(FileName): ''' Loads hollow data into structured numpy array of floats,", "returns a tuple of column headers along with the structured array. ''' data", "import numpy as np def LoadData(FileName): ''' Loads hollow data into structured numpy", "hollow data into structured numpy array of floats and returns a tuple of", "into structured numpy array of floats, and splits the data into separate structured", "def DataFilter(DataFile, Parameter, Value): ''' Split hollows around Value of a given property.", "''' Loads hollow data into structured numpy array of floats and returns a", "Parameter, Value): ''' Split hollows around Value of a given property. returns Small", "Headers, A = LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] ==", "by aspect band and returns a tuple of column headers along with the", "and splits the data into separate structured arrays by aspect band and returns", "band and returns a tuple of column headers along with the structured arrays.", "E = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)] W = A[(A['Aspect'] >", "''' data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads", "LoadData(FileName): ''' Loads hollow data into structured numpy array of floats and returns", "data into separate structured arrays by aspect band and returns a tuple of", "NE = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 85)] SE = A[(A['Aspect'] >", "Value): ''' Split hollows around Value of a given property. returns Small and", "A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] == 3)]['ID']", "IDs corresponding to specific vegetation types ''' Headers, A = LoadData(DataFile) a =", "hollow data into structured numpy array of floats, and splits the data into", "2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg'] == 4)]['ID'] return a,", "and below the median. ''' Headers, A = LoadData(DataFile) Small = A[(A[Parameter] <", "np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow data into", "E, W def DataFilter(DataFile, Parameter, Value): ''' Split hollows around Value of a", "b = A[(A['Veg'] == 2)]['ID'] c = A[(A['Veg'] == 3)]['ID'] d = A[(A['Veg']", "tuple of column headers along with the structured array. ''' data = np.genfromtxt(FileName,", "headers along with the structured arrays. ''' Headers, A = LoadData(FileName) NE =", "numpy array of floats, and splits the data into separate structured arrays by", "0) & (A['Aspect'] <= 85)] SE = A[(A['Aspect'] > 85) & (A['Aspect'] <=", "= A[(A['Aspect'] > 165)] return Headers, NE, SE, E, W def DataFilter(DataFile, Parameter,", "and returns a tuple of column headers along with the structured arrays. '''", "the structured arrays. ''' Headers, A = LoadData(FileName) NE = A[(A['Aspect'] >= 0)", "of column headers along with the structured array. ''' data = np.genfromtxt(FileName, names=True,", "returns a tuple of column headers along with the structured arrays. ''' Headers,", "of column headers along with the structured arrays. ''' Headers, A = LoadData(FileName)", "Split hollows into vegetation categories of a given property. returns 4 lists of", "<= 165)] E = A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)] W =", "data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow", "A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return Small, Large def VegDataFilter(DataFile):", "two lists of IDs corresponding to hollows above and below the median. '''", "hollows into vegetation categories of a given property. returns 4 lists of IDs", "above and below the median. ''' Headers, A = LoadData(DataFile) Small = A[(A[Parameter]", "LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c =", "below the median. ''' Headers, A = LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID']", "= np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow data", "A = LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID']", "floats, and splits the data into separate structured arrays by aspect band and", "structured arrays. ''' Headers, A = LoadData(FileName) NE = A[(A['Aspect'] >= 0) &", "Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return Small, Large def VegDataFilter(DataFile): ''' Split", "median. ''' Headers, A = LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large =", "= LoadData(DataFile) a = A[(A['Veg'] == 1)]['ID'] b = A[(A['Veg'] == 2)]['ID'] c", "arrays by aspect band and returns a tuple of column headers along with", "LoadData(DataFile) Small = A[(A[Parameter] < Value)]['ID'] Large = A[(A[Parameter] >= Value)]['ID'] return Small,", "headers along with the structured array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',') return", "names=True, delimiter=',') return data.dtype.names, data def SegmentDataByAspect(FileName): ''' Loads hollow data into structured", "the structured array. ''' data = np.genfromtxt(FileName, names=True, delimiter=',') return data.dtype.names, data def", "given property. returns Small and Large, two lists of IDs corresponding to hollows", "structured arrays by aspect band and returns a tuple of column headers along", "Large, two lists of IDs corresponding to hollows above and below the median.", "= A[(A['Aspect'] >= 0) & (A['Aspect'] <= 165)] W = A[(A['Aspect'] > 165)]", "categories of a given property. returns 4 lists of IDs corresponding to specific", "and Large, two lists of IDs corresponding to hollows above and below the" ]
[ "get_include(): ''' Path of cython headers for compiling cython modules ''' return os.path.dirname(os.path.abspath(__file__))", "def get_include(): ''' Path of cython headers for compiling cython modules ''' return", ".version import __version__ def get_include(): ''' Path of cython headers for compiling cython", "__version__ def get_include(): ''' Path of cython headers for compiling cython modules '''", "os from .version import __version__ def get_include(): ''' Path of cython headers for", "from .version import __version__ def get_include(): ''' Path of cython headers for compiling", "import os from .version import __version__ def get_include(): ''' Path of cython headers", "import __version__ def get_include(): ''' Path of cython headers for compiling cython modules" ]
[ "expect(res, expect): global testno if res != expect: print \"Expected\", repr(expect), \"got\", repr(res)", "expect): global testno if res != expect: print \"Expected\", repr(expect), \"got\", repr(res) print", "print \"Expected\", repr(expect), \"got\", repr(res) print \"not\", print \"ok\", testno testno = testno", "} } \"\"\") foo = perl.eval(\"\\&foo\") testno = 1 def expect(res, expect): global", "foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None), void)", "print \"1..11\" perl.eval(\"\"\" sub foo { if (wantarray) { return \"array\"; } elsif", "scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1; expect(foo(),", "expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1; expect(foo(), array)", "(wantarray) { return \"array\"; } elsif (defined wantarray) { return \"scalar\"; } else", "expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array)", "\"scalar\"; } else { return; } } \"\"\") foo = perl.eval(\"\\&foo\") testno =", "0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar)", "= None), void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\",", "# print \"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo { if", "1 void = None scalar = \"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__", "testno if res != expect: print \"Expected\", repr(expect), \"got\", repr(res) print \"not\", print", "wantarray) { return \"scalar\"; } else { return; } } \"\"\") foo =", "if res != expect: print \"Expected\", repr(expect), \"got\", repr(res) print \"not\", print \"ok\",", "elsif (defined wantarray) { return \"scalar\"; } else { return; } } \"\"\")", "foo = perl.eval(\"\\&foo\") testno = 1 def expect(res, expect): global testno if res", "raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo { if (wantarray) { return \"array\";", "void = None scalar = \"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ =", "testno = 1 def expect(res, expect): global testno if res != expect: print", "import perl #if perl.MULTI_PERL: # print \"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\"", "repr(res) print \"not\", print \"ok\", testno testno = testno + 1 void =", "= 1 def expect(res, expect): global testno if res != expect: print \"Expected\",", "if (wantarray) { return \"array\"; } elsif (defined wantarray) { return \"scalar\"; }", "perl.eval(\"\"\" sub foo { if (wantarray) { return \"array\"; } elsif (defined wantarray)", "= 1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__", "None), void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__", "} else { return; } } \"\"\") foo = perl.eval(\"\\&foo\") testno = 1", "expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1), array) expect(perl.call_tuple(\"foo\", __wantarray__", "+ 1 void = None scalar = \"scalar\" array = (\"array\",) expect(foo(), scalar)", "\"ok\", testno testno = testno + 1 void = None scalar = \"scalar\"", "void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1), array) expect(perl.call_tuple(\"foo\", __wantarray__ =", "testno testno = testno + 1 void = None scalar = \"scalar\" array", "\"array\"; } elsif (defined wantarray) { return \"scalar\"; } else { return; }", "= (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__", "foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1),", "return; } } \"\"\") foo = perl.eval(\"\\&foo\") testno = 1 def expect(res, expect):", "{ return; } } \"\"\") foo = perl.eval(\"\\&foo\") testno = 1 def expect(res,", "= None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1), array)", "SystemExit print \"1..11\" perl.eval(\"\"\" sub foo { if (wantarray) { return \"array\"; }", "{ return \"array\"; } elsif (defined wantarray) { return \"scalar\"; } else {", "testno = testno + 1 void = None scalar = \"scalar\" array =", "testno + 1 void = None scalar = \"scalar\" array = (\"array\",) expect(foo(),", "perl #if perl.MULTI_PERL: # print \"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\" sub", "expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1;", "res != expect: print \"Expected\", repr(expect), \"got\", repr(res) print \"not\", print \"ok\", testno", "expect: print \"Expected\", repr(expect), \"got\", repr(res) print \"not\", print \"ok\", testno testno =", "array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None expect(foo(),", "def expect(res, expect): global testno if res != expect: print \"Expected\", repr(expect), \"got\",", "None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1), array) expect(perl.call_tuple(\"foo\",", "scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"),", "= 1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__", "array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None), void)", "\"\"\") foo = perl.eval(\"\\&foo\") testno = 1 def expect(res, expect): global testno if", "else { return; } } \"\"\") foo = perl.eval(\"\\&foo\") testno = 1 def", "expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None", "\"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo { if (wantarray) {", "\"got\", repr(res) print \"not\", print \"ok\", testno testno = testno + 1 void", "sub foo { if (wantarray) { return \"array\"; } elsif (defined wantarray) {", "print \"ok\", testno testno = testno + 1 void = None scalar =", "= perl.eval(\"\\&foo\") testno = 1 def expect(res, expect): global testno if res !=", "return \"scalar\"; } else { return; } } \"\"\") foo = perl.eval(\"\\&foo\") testno", "void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ =", "= None scalar = \"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1),", "(defined wantarray) { return \"scalar\"; } else { return; } } \"\"\") foo", "expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar)", "1 def expect(res, expect): global testno if res != expect: print \"Expected\", repr(expect),", "None), void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ =", "\"Expected\", repr(expect), \"got\", repr(res) print \"not\", print \"ok\", testno testno = testno +", "print \"not\", print \"ok\", testno testno = testno + 1 void = None", "None scalar = \"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array)", "= 0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None expect(foo(), void) expect(perl.call(\"foo\"),", "} \"\"\") foo = perl.eval(\"\\&foo\") testno = 1 def expect(res, expect): global testno", "1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ =", "\"1..11\" perl.eval(\"\"\" sub foo { if (wantarray) { return \"array\"; } elsif (defined", "array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ = 0),", "\"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None),", "\"not\", print \"ok\", testno testno = testno + 1 void = None scalar", "{ return \"scalar\"; } else { return; } } \"\"\") foo = perl.eval(\"\\&foo\")", "global testno if res != expect: print \"Expected\", repr(expect), \"got\", repr(res) print \"not\",", "void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None),", "{ if (wantarray) { return \"array\"; } elsif (defined wantarray) { return \"scalar\";", "print \"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo { if (wantarray)", "return \"array\"; } elsif (defined wantarray) { return \"scalar\"; } else { return;", "expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = None expect(foo(), void)", "#if perl.MULTI_PERL: # print \"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo", "scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1), array) expect(perl.call_tuple(\"foo\", __wantarray__ = 0), scalar)", "= \"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ =", "foo { if (wantarray) { return \"array\"; } elsif (defined wantarray) { return", "<filename>extra-packages/pyperl-1.0.1d/t/wantarray.py import perl #if perl.MULTI_PERL: # print \"1..0\" # raise SystemExit print \"1..11\"", "perl.eval(\"\\&foo\") testno = 1 def expect(res, expect): global testno if res != expect:", "1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ =", "repr(expect), \"got\", repr(res) print \"not\", print \"ok\", testno testno = testno + 1", "} elsif (defined wantarray) { return \"scalar\"; } else { return; } }", "(\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__ = None), void) foo.__wantarray__ =", "expect(perl.call(\"foo\"), scalar) expect(perl.call_tuple(\"foo\"), array) expect(perl.call(\"foo\", __wantarray__ = 1), array) expect(perl.call_tuple(\"foo\", __wantarray__ = 0),", "!= expect: print \"Expected\", repr(expect), \"got\", repr(res) print \"not\", print \"ok\", testno testno", "scalar = \"scalar\" array = (\"array\",) expect(foo(), scalar) expect(foo(__wantarray__ = 1), array) expect(foo(__wantarray__", "= None), void) foo.__wantarray__ = 1; expect(foo(), array) expect(foo(__wantarray__ = 0), scalar) expect(foo(__wantarray__", "= testno + 1 void = None scalar = \"scalar\" array = (\"array\",)", "# raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo { if (wantarray) { return", "perl.MULTI_PERL: # print \"1..0\" # raise SystemExit print \"1..11\" perl.eval(\"\"\" sub foo {" ]
[ "o {}º Valor: '.format(c))) if valor % 2 == 0: d += valor", "{}º Valor: '.format(c))) if valor % 2 == 0: d += valor co", "+= valor co += 1 print('Você informou {} números PARES e a soma", "d += valor co += 1 print('Você informou {} números PARES e a", "valor = int(input('Digite o {}º Valor: '.format(c))) if valor % 2 == 0:", "Valor: '.format(c))) if valor % 2 == 0: d += valor co +=", "= 0 for c in range(1, 7): valor = int(input('Digite o {}º Valor:", "0: d += valor co += 1 print('Você informou {} números PARES e", "= int(input('Digite o {}º Valor: '.format(c))) if valor % 2 == 0: d", "range(1, 7): valor = int(input('Digite o {}º Valor: '.format(c))) if valor % 2", "= 0 co = 0 for c in range(1, 7): valor = int(input('Digite", "2 == 0: d += valor co += 1 print('Você informou {} números", "0 co = 0 for c in range(1, 7): valor = int(input('Digite o", "for c in range(1, 7): valor = int(input('Digite o {}º Valor: '.format(c))) if", "in range(1, 7): valor = int(input('Digite o {}º Valor: '.format(c))) if valor %", "int(input('Digite o {}º Valor: '.format(c))) if valor % 2 == 0: d +=", "'.format(c))) if valor % 2 == 0: d += valor co += 1", "d = 0 co = 0 for c in range(1, 7): valor =", "0 for c in range(1, 7): valor = int(input('Digite o {}º Valor: '.format(c)))", "valor % 2 == 0: d += valor co += 1 print('Você informou", "+= 1 print('Você informou {} números PARES e a soma foi {}'.format(co, d))", "7): valor = int(input('Digite o {}º Valor: '.format(c))) if valor % 2 ==", "<gh_stars>0 d = 0 co = 0 for c in range(1, 7): valor", "% 2 == 0: d += valor co += 1 print('Você informou {}", "if valor % 2 == 0: d += valor co += 1 print('Você", "== 0: d += valor co += 1 print('Você informou {} números PARES", "c in range(1, 7): valor = int(input('Digite o {}º Valor: '.format(c))) if valor", "co = 0 for c in range(1, 7): valor = int(input('Digite o {}º", "co += 1 print('Você informou {} números PARES e a soma foi {}'.format(co,", "valor co += 1 print('Você informou {} números PARES e a soma foi" ]
[ "if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm", "depth map in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if", "import join import cv2 import pickle import torch import numpy as np import", "0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return", "= self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1)", "open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f) # fetch ground truth depth map", "os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000 # fetch normal map in", "- 1) * 2 - 1 normal = normal[:, :, ::-1] # fetch", "normal[:, :, ::-1] # fetch rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name),", "np.load(label_path) return depth_gt, depth_pred, label, normal, img if __name__ == \"__main__\": root_dir =", "= depth_ext self.normal_ext = normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def", "16 - 1) * 2 - 1 normal = normal[:, :, ::-1] #", "1 normal = normal[:, :, ::-1] # fetch rgb image image_path = join(self.root_dir,", "'{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) /", "self.im_ext)) img = cv2.imread(image_path, -1) / 255 img = img[:, :, ::-1] #", "# fetch ground truth depth map in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'],", "_fetch_data(self, index): # fetch predicted depth map in meters depth_pred_path = join(self.root_dir, self.pred_dir,", "= root_dir self.label_name = label_name self.method_name = method_name self.im_ext = im_ext self.gt_dir =", "= torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img", "'{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f) # fetch ground truth", "'{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred, label, normal, img if __name__", "normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def", "(2 ** 16 - 1) * 2 - 1 normal = normal[:, :,", "import torch import numpy as np import pandas as pd import torch.utils.data as", "join import cv2 import pickle import torch import numpy as np import pandas", "f: depth_pred = pickle.load(f) # fetch ground truth depth map in meters depth_gt_path", "-1) / (2 ** 16 - 1) * 2 - 1 normal =", "pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir", "= img[:, :, ::-1] # fetch occlusion orientation labels label_path = join(self.root_dir, self.label_dir,", "DataLoader import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)):", "= join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred,", "= DataLoader(dataset, batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)): if i == 0:", "data in tqdm(enumerate(test_loader)): if i == 0: print(data[0].shape, data[1].shape, data[2].shape, data[3].shape, data[4].shape) sys.exit()", "normal map in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext))", "depth_gt = cv2.imread(depth_gt_path, -1) / 1000 # fetch normal map in norm-1 vectors", "InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from torch.utils.data import DataLoader import sys test_loader", "label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir =", "as f: depth_pred = pickle.load(f) # fetch ground truth depth map in meters", "self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) / 255 img = img[:, :,", "join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred, label,", "tqdm from torch.utils.data import DataLoader import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for", "2 - 1 normal = normal[:, :, ::-1] # fetch rgb image image_path", "torch import numpy as np import pandas as pd import torch.utils.data as data", "from tqdm import tqdm from torch.utils.data import DataLoader import sys test_loader = DataLoader(dataset,", "self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self,", "fetch normal map in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'],", "numpy as np import pandas as pd import torch.utils.data as data class InteriorNet(data.Dataset):", "im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name = label_name self.method_name =", "= label_name self.method_name = method_name self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir =", "torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label, normal,", "depth_pred = pickle.load(f) # fetch ground truth depth map in meters depth_gt_path =", "fetch ground truth depth map in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name),", "1) * 2 - 1 normal = normal[:, :, ::-1] # fetch rgb", "label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt,", "print(len(dataset)) from tqdm import tqdm from torch.utils.data import DataLoader import sys test_loader =", "1) return depth_gt, depth_pred, label, normal, img def _fetch_data(self, index): # fetch predicted", "label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self, index): depth_gt,", "255 img = img[:, :, ::-1] # fetch occlusion orientation labels label_path =", "np import pandas as pd import torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self,", "'{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000 #", "map in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal", "__getitem__(self, index): depth_gt, depth_pred, label, normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred", "test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)): if i ==", "1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label, normal, img def", "with open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f) # fetch ground truth depth", "# fetch occlusion orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext))", "index): # fetch predicted depth map in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'],", "truth depth map in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext))", "join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred =", "tqdm import tqdm from torch.utils.data import DataLoader import sys test_loader = DataLoader(dataset, batch_size=4,", "from torch.utils.data import DataLoader import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i,", "depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f:", "return len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label, normal, img = self._fetch_data(index) depth_gt", "= im_ext self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext =", "gt_dir self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext", "1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt,", "import pandas as pd import torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self, root_dir,", "pickle.load(f) # fetch ground truth depth map in meters depth_gt_path = join(self.root_dir, self.gt_dir,", "# fetch rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img", "img if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from", "torch.utils.data import DataLoader import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i, data", "self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt'))", "import torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data',", "return depth_gt, depth_pred, label, normal, img if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet'", "= torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label,", "'{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2 ** 16 - 1) *", "shuffle=False) for i, data in tqdm(enumerate(test_loader)): if i == 0: print(data[0].shape, data[1].shape, data[2].shape,", "/ 1000 # fetch normal map in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir,", "orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path)", "- 1 normal = normal[:, :, ::-1] # fetch rgb image image_path =", "import DataLoader import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i, data in", "img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label, normal, img def _fetch_data(self,", "method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name", "label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name = label_name self.method_name = method_name self.im_ext", "label, normal, img def _fetch_data(self, index): # fetch predicted depth map in meters", "join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2 **", "= normal[:, :, ::-1] # fetch rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'],", "= join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) / 255", "depth_pred, label, normal, img if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset =", "/ (2 ** 16 - 1) * 2 - 1 normal = normal[:,", "= join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2", "img = cv2.imread(image_path, -1) / 255 img = img[:, :, ::-1] # fetch", "rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path,", "self.root_dir = root_dir self.label_name = label_name self.method_name = method_name self.im_ext = im_ext self.gt_dir", "root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from torch.utils.data", "-1) / 255 img = img[:, :, ::-1] # fetch occlusion orientation labels", "fetch rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img =", "os from os.path import join import cv2 import pickle import torch import numpy", "map in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not", "os.path import join import cv2 import pickle import torch import numpy as np", "= np.load(label_path) return depth_gt, depth_pred, label, normal, img if __name__ == \"__main__\": root_dir", "self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f) # fetch", "self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self, index): depth_gt, depth_pred,", "index): depth_gt, depth_pred, label, normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred =", "torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1)", "meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path)", "normal, img if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset))", "InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'):", "self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f) #", "normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name = label_name self.method_name", "self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2 ** 16", "pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label, normal,", "self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred, label, normal, img if __name__ ==", "== \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm", "torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png',", "__init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__()", "= cv2.imread(image_path, -1) / 255 img = img[:, :, ::-1] # fetch occlusion", "depth_pred, label, normal, img def _fetch_data(self, index): # fetch predicted depth map in", "depth_gt, depth_pred, label, normal, img def _fetch_data(self, index): # fetch predicted depth map", "root_dir self.label_name = label_name self.method_name = method_name self.im_ext = im_ext self.gt_dir = gt_dir", ":, ::-1] # fetch occlusion orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name),", "depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt", "import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)): if", "= '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from torch.utils.data import", "norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path,", "i, data in tqdm(enumerate(test_loader)): if i == 0: print(data[0].shape, data[1].shape, data[2].shape, data[3].shape, data[4].shape)", "im_ext self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext", "0, 1) return depth_gt, depth_pred, label, normal, img def _fetch_data(self, index): # fetch", "data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png',", "depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1)", "if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000 # fetch normal", "depth_pred, label, normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label", "depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal =", "DataLoader(dataset, batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)): if i == 0: print(data[0].shape,", "label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext = label_ext", "def _fetch_data(self, index): # fetch predicted depth map in meters depth_pred_path = join(self.root_dir,", "/ 255 img = img[:, :, ::-1] # fetch occlusion orientation labels label_path", "cv2 import pickle import torch import numpy as np import pandas as pd", "from os.path import join import cv2 import pickle import torch import numpy as", "self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext", "'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label, normal, img", "normal = cv2.imread(normal_path, -1) / (2 ** 16 - 1) * 2 -", "* 2 - 1 normal = normal[:, :, ::-1] # fetch rgb image", "'{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) / 255 img = img[:, :, ::-1]", "0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label, normal, img", "self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext", "as data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png',", "label, normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label =", "= method_name self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir =", "import pickle import torch import numpy as np import pandas as pd import", "# fetch predicted depth map in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name,", "len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label, normal, img = self._fetch_data(index) depth_gt =", "def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet,", "= join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred", "root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir", "label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name = label_name self.method_name = method_name", "class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred', gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label',", "vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1)", "= torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0,", "self.label_name = label_name self.method_name = method_name self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir", "join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path,", "map in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path,", "= join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt =", "'/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from torch.utils.data import DataLoader", "'{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred, label, normal, img", "** 16 - 1) * 2 - 1 normal = normal[:, :, ::-1]", "meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as", "label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2,", "import os from os.path import join import cv2 import pickle import torch import", "::-1] # fetch occlusion orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'],", "pickle import torch import numpy as np import pandas as pd import torch.utils.data", "return depth_gt, depth_pred, label, normal, img def _fetch_data(self, index): # fetch predicted depth", "depth map in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with", "'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f) # fetch ground", "'{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) / 255 img = img[:,", "labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return", "'rb') as f: depth_pred = pickle.load(f) # fetch ground truth depth map in", "= label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self, index):", "self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal", "img[:, :, ::-1] # fetch occlusion orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'],", "batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)): if i == 0: print(data[0].shape, data[1].shape,", "label = np.load(label_path) return depth_gt, depth_pred, label, normal, img if __name__ == \"__main__\":", "for i, data in tqdm(enumerate(test_loader)): if i == 0: print(data[0].shape, data[1].shape, data[2].shape, data[3].shape,", "= label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext =", "= pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label,", "predicted depth map in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image']))", "in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb')", "self.method_name = method_name self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir", "in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal =", "self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000", "normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) /", "normal, img def _fetch_data(self, index): # fetch predicted depth map in meters depth_pred_path", "def __getitem__(self, index): depth_gt, depth_pred, label, normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0)", "import tqdm from torch.utils.data import DataLoader import sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False)", "sys test_loader = DataLoader(dataset, batch_size=4, shuffle=False) for i, data in tqdm(enumerate(test_loader)): if i", "join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) / 255 img", "super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name = label_name self.method_name = method_name self.im_ext =", "method_name self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir = label_dir self.pred_dir = pred_dir", "self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext = label_ext self.df", "in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path):", "fetch predicted depth map in meters depth_pred_path = join(self.root_dir, self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data',", "self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred, label, normal,", "gt_dir='data', depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name =", "= cv2.imread(depth_gt_path, -1) / 1000 # fetch normal map in norm-1 vectors normal_path", "def __len__(self): return len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label, normal, img =", "::-1] # fetch rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext))", "self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label = np.load(label_path) return depth_gt, depth_pred, label, normal, img if", "label, normal, img if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir)", "as np import pandas as pd import torch.utils.data as data class InteriorNet(data.Dataset): def", "pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir,", "self.pred_dir, self.df.iloc[index]['scene'], self.method_name, 'data', '{}.pkl'.format(self.df.iloc[index]['image'])) with open(depth_pred_path, 'rb') as f: depth_pred = pickle.load(f)", "normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img = torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred,", "fetch occlusion orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label", "torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0,", "label_name self.method_name = method_name self.im_ext = im_ext self.gt_dir = gt_dir self.label_dir = label_dir", "= InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from torch.utils.data import DataLoader import sys", "depth_gt, depth_pred, label, normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0)", "normal, img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2,", "import numpy as np import pandas as pd import torch.utils.data as data class", "depth_ext self.normal_ext = normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self):", "occlusion orientation labels label_path = join(self.root_dir, self.label_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.label_ext)) label =", "\"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from", "img def _fetch_data(self, index): # fetch predicted depth map in meters depth_pred_path =", ":, ::-1] # fetch rgb image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'],", "dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import tqdm from torch.utils.data import DataLoader import", "= torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2,", "torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0, 1) normal = torch.from_numpy(np.ascontiguousarray(normal)).float().permute(2, 0, 1) img =", "__len__(self): return len(self.df) def __getitem__(self, index): depth_gt, depth_pred, label, normal, img = self._fetch_data(index)", "= pickle.load(f) # fetch ground truth depth map in meters depth_gt_path = join(self.root_dir,", "= torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label, normal, img def _fetch_data(self, index):", "'{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2 ** 16 -", "img = self._fetch_data(index) depth_gt = torch.from_numpy(np.ascontiguousarray(depth_gt)).float().unsqueeze(0) depth_pred = torch.from_numpy(np.ascontiguousarray(depth_pred)).float().unsqueeze(0) label = torch.from_numpy(np.ascontiguousarray(label)).float().permute(2, 0,", "cv2.imread(depth_gt_path, -1) / 1000 # fetch normal map in norm-1 vectors normal_path =", "print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000 # fetch normal map in norm-1", "img = img[:, :, ::-1] # fetch occlusion orientation labels label_path = join(self.root_dir,", "__name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset = InteriorNet(root_dir) print(len(dataset)) from tqdm import", "torch.from_numpy(np.ascontiguousarray(img)).float().permute(2, 0, 1) return depth_gt, depth_pred, label, normal, img def _fetch_data(self, index): #", "self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1)", "self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2 ** 16 - 1)", "image image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1)", "= cv2.imread(normal_path, -1) / (2 ** 16 - 1) * 2 - 1", "self.normal_ext = normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return", "self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext", "normal = normal[:, :, ::-1] # fetch rgb image image_path = join(self.root_dir, self.gt_dir,", "-1) / 1000 # fetch normal map in norm-1 vectors normal_path = join(self.root_dir,", "cv2.imread(image_path, -1) / 255 img = img[:, :, ::-1] # fetch occlusion orientation", "not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000 # fetch normal map", "self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) / 255 img =", "depth_ext='-depth-plane.png', normal_ext='-normal.png', im_ext='-rgb.png', label_dir='label', label_ext='-order-pix.npy'): super(InteriorNet, self).__init__() self.root_dir = root_dir self.label_name = label_name", "1000 # fetch normal map in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'],", "ground truth depth map in meters depth_gt_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'],", "self.normal_ext)) normal = cv2.imread(normal_path, -1) / (2 ** 16 - 1) * 2", "= normal_ext self.label_ext = label_ext self.df = pd.read_csv(join(root_dir, 'InteriorNet.txt')) def __len__(self): return len(self.df)", "depth_gt, depth_pred, label, normal, img if __name__ == \"__main__\": root_dir = '/space_sdd/InteriorNet' dataset", "cv2.imread(normal_path, -1) / (2 ** 16 - 1) * 2 - 1 normal", "# fetch normal map in norm-1 vectors normal_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name),", "import cv2 import pickle import torch import numpy as np import pandas as", "= gt_dir self.label_dir = label_dir self.pred_dir = pred_dir self.depth_ext = depth_ext self.normal_ext =", "as pd import torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred',", "image_path = join(self.root_dir, self.gt_dir, '{}{}'.format(self.df.iloc[index]['scene'], self.label_name), '{:04d}{}'.format(self.df.iloc[index]['image'], self.im_ext)) img = cv2.imread(image_path, -1) /", "self.depth_ext)) if not os.path.exists(depth_gt_path): print(depth_gt_path) depth_gt = cv2.imread(depth_gt_path, -1) / 1000 # fetch", "= pred_dir self.depth_ext = depth_ext self.normal_ext = normal_ext self.label_ext = label_ext self.df =", "pd import torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2', pred_dir='pred', method_name='sharpnet_pred',", "pandas as pd import torch.utils.data as data class InteriorNet(data.Dataset): def __init__(self, root_dir, label_name='_raycastingV2',", "self).__init__() self.root_dir = root_dir self.label_name = label_name self.method_name = method_name self.im_ext = im_ext" ]
[ "points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and save it's color self.paint_polygon_(polygon, self.color)", "0 occultation_mask[occultation_mask == 1] = 0 \"\"\" if self.finish_callback: # TODO: fix this", "too close to any other already chosen point dist = self.get_distance(pt, pos) if", "0, 100) else: qc = QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc)", "tmp_points def merge_images(self): \"\"\" merges the 3 images (paint, polygons and circles) into", "button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode =", "- occultation, 255 - visible spot # 1) load BLUE channel (blue color", "and i < bg_width and j > 0 and j <= bg_height: try:", "new pen size :return: None \"\"\" # change pen size self.pen_size = value", "self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\")", "event position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if self.mode", "self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set", "TODO: fix this so two different masks can be used # self.finish_callback(arena_mask, occultation_mask)", "not pos: # if pos isn't in the scene return if self.mode ==", "import QtGui, QtCore import cv2 import sys import math import numpy as np", "needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False)", "and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw", "finish_callback=None): # TODO: add support for the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor,", "dist < precision: print(\"Too close2\") ok = False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode", "tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\" merges the 3 images (paint, polygons", "is a separate method purely to save space :return: None \"\"\" ########################## #", "self.mode == \"polygons\": return self.set_polygons_mode() else: # don't do anything if polygons mode", ":return: bool, whether the polygon was drawn \"\"\" # check if polygon can", "circles) into one result :return: the final image \"\"\" bg_height, bg_width = self.background.shape[:2]", "app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project()", "== \"Polygon mode\": # don't do anything if polygons mode is already active", "the scene return if self.mode == \"polygons\": # in the polygons mode, try", "is already active if self.mode == \"paint\": return self.set_paint_mode() elif value == \"Polygon", "to create a mask. Mysteriously, # TODO: alpha channel seems to be working", "step) self.backup = [] ########################## # PAINT MODE VARIABLES # ########################## self.pen_size =", "return arena_mask, None def change_pen_size(self, value): \"\"\" change pen size :param value: new", "def switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting color to %s\" % text))", "checks if the point is inside the scene :param point: Qpoint or QPointF", "QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300)", "widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE", "QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut self.action_clear =", "point in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self):", "= [] # cleanup after paint mode is not needed self.mode = \"circles\"", "and polygons self.remove_items() # - clear the memory self.point_items = [] self.polygon_points =", "width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor!", "# cleanup after paint mode is not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False)", "extract mask data, only Red (0) and Blue (2) channels are needed. #", "save space :return: None \"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) #", "= [] def mouse_press_event(self, event): # get event position and calibrate to scene", "\"\"\" # save last 10 images img = self.paint_image.copy() self.backup.append(img) if len(self.backup) >", "merge_images(self): \"\"\" merges the 3 images (paint, polygons and circles) into one result", "self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal,", "< precision: print(\"Too close2\") ok = False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode ==", "[] self.polygon_colors = [] def mouse_press_event(self, event): # get event position and calibrate", "self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut self.action_paint_polygon", "\"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary", "print(\"Too close2\") ok = False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": #", "share the same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set", "self.background = img self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene()", "result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0,", "use current pen color if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255,", "already active if self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self): # join the", "self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary images", "in occultation_mask means that the point is NOT a place to hide (it", "independent points for point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything and", "point_items in self.polygon_points: for point in point_items: self.scene.removeItem(point) # erase all independent points", "except: pass # set new image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b):", "time. (they both share the same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan)", "0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and left panel with", "self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self): \"\"\" remove all points from polygons", "value = QtGui.qRgba(0, 0, 0, 0) # paint the area around the point", "self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button =", "bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0,", "def merge_images(self): \"\"\" merges the 3 images (paint, polygons and circles) into one", "yet part of any polygon) self.point_items = [] # type MyEllipse[] # holds", "current image temporarily (to use with \"undo()\" later) :return: \"\"\" # save last", "all used points. Each list corresponds to one polygon self.polygon_points = [] #", "= self.background.shape[:2] for i in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for j", "fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES", "painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the", "pen size :param value: new pen size :return: None \"\"\" # change pen", "value = QtGui.qRgba(0, 0, 255, 100) elif self.color == \"Outside of\\nthe arena\": value", "mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen as a color, switch it", "(value 1) to 0 arena_mask[arena_mask == 1] = 0 # invert mask arena_mask", "Each list corresponds to one polygon self.polygon_points = [] # type MyEllipse[][] #", "to 1 (temporary) occultation_mask[occultation_mask > 0] = 1 # 3) set all pixels", "1) load RED channel (red color shows where outside of the arena is", "in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\"", "(it is visible) \"\"\" img = self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr =", "(arena inside) to 255 occultation_mask[occultation_mask == 0] = 255 # 4) set all", "a pen in paint mode :param point: point to be drawn :return: None", "known :param polygon: QPolygonF to be painted :param color: \"Red\" or \"Blue\" :return:", "be pushed in paint mode, but affects polygon painting too (all polygons are", "# change pen size self.pen_size = value # refresh text in QLabel self.set_label_text()", "polygons mode from the scene :return: \"\"\" # erase all points from polygons", "to work with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap", "self.get_distance(pt, pos) if dist < precision: print(\"Too close2\") ok = False if ok:", "None \"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget", "ok = False for points in self.polygon_points: for pt in points: dist =", "== 1] = 0 \"\"\" if self.finish_callback: # TODO: fix this so two", "1 (temporary) occultation_mask[occultation_mask > 0] = 1 # 3) set all pixels with", "don't do anything if paint mode is already active if self.mode == \"paint\":", "bg_height: try: self.paint_image.setPixel(i, j, value) except: pass # set new image and pixmap", "########################## # PAINT MODE VARIABLES # ########################## self.pen_size = 30 # image to", "after circle drawing # cleanup after paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False)", "\"\"\" paint a point with a pen in paint mode :param point: point", "point.toPoint() # use current pen color if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0,", "\"\"\" changes the label to show current pen settings :return: None \"\"\" if", "self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text()", "be created if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete, drawing it\") #", "True in occultation_mask means that the point is NOT a place to hide", "self.clear_paint_image() self.point_items = [] self.polygon_points = [] self.polygon_colors = [] def mouse_press_event(self, event):", "i in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for j in range(point.y() -", "self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create", "elif value == \"Polygon mode\": # don't do anything if polygons mode is", "the point position bg_height, bg_width = self.background.shape[:2] for i in range(point.x() - self.pen_size/2,", "all points from polygons for point_items in self.polygon_points: for point in point_items: self.scene.removeItem(point)", "arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img", "as np from core.project.project import Project from gui.img_controls import gui_utils from gui.arena.my_ellipse import", "clicked pos isn't too close to any other already chosen point dist =", "__name__ == \"__main__\": app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png')", "self.mode = \"polygons\" # TODO: add cleanup after circle drawing # cleanup after", "-> everything not red is inside) # TODO: For some reason, color channels", "memory self.point_items = [] self.polygon_points = [] self.polygon_colors = [] # TODO: add", "10: self.backup.pop(0) def undo(self): if self.mode == \"paint\": lenght = len(self.backup) if lenght", "self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the points (ellipses), too self.polygon_points.append(self.point_items) # clear", "== \"__main__\": app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p", "to support the \"undo\" function # undo button can only be pushed in", "numpy as np from core.project.project import Project from gui.img_controls import gui_utils from gui.arena.my_ellipse", "polygons self.remove_items() # - clear the memory self.point_items = [] self.polygon_points = []", "to show current pen settings :return: None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen", "# complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv)", "self.DEBUG: print((\"Setting color to %s\" % text)) # make sure no other button", "% text)) # make sure no other button stays pushed for button in", "polygons mode is already active if self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self):", "= QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label)", "+= 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in self.point_items: pos = QtCore.QPoint(point.x(),", "i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in self.point_items: pos =", "means that the point is INSIDE the arena True in occultation_mask means that", "\"\"\" converts image to numpy arrays :return: tuple (arena_mask, occultation_mask) True in arena_masks", "# To extract mask data, only Red (0) and Blue (2) channels are", "and calibrate to scene pos = self.get_event_pos(event) if not pos: # if pos", "self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in the paint mode, paint the event", "and use blue to mark possible\" \" hiding places. Unresolvable colors will be", "\"\"\" paints a polygon, when it's color and position are known :param polygon:", "self.make_gui() def switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting color to %s\" %", "mode :param point: point to be drawn :return: None \"\"\" # change float", "complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv) #", "has chosen to be a future part of a polygon :param position: :return:", "= QtGui.QColor(255, 0, 0, 100) else: qc = QtGui.QColor(0, 0, 255, 100) pen", "self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon)", "1] = 0 \"\"\" if self.finish_callback: # TODO: fix this so two different", "to be working well, uncomment later return arena_mask, None def change_pen_size(self, value): \"\"\"", "points\") return False def paint_polygon_(self, polygon, color): \"\"\" paints a polygon, when it's", "None) else: # print label(arena_mask, connectivity=2) # TODO: label seems to be working", "show current pen settings :return: None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size:", "== \"polygons\": return self.set_polygons_mode() else: # don't do anything if polygons mode is", "(blue color shows where occultation is -> everything not blue is visible or", "\"Red\" or \"Blue\" self.polygon_colors = [] # type string[] # holds sets of", "\"polygons\" mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else:", "in polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen as a color,", "point position bg_height, bg_width = self.background.shape[:2] for i in range(point.x() - self.pen_size/2, point.x()", "20 ok = True for pt in self.point_items: # check if the clicked", "of all used points. Each list corresponds to one polygon self.polygon_points = []", "from currently selected points (MyEllipses) :return: bool, whether the polygon was drawn \"\"\"", "arena True in occultation_mask means that the point is NOT a place to", "slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3)", "fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0,", "# 2) set all pixels that contain at least a little blue to", "mask data, only Red (0) and Blue (2) channels are needed. # Create", "mask cannot be used at the same time. (they both share the same", "0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES # ##########################", "image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the polygons that are now changeable.", "is_in_scene(self, point): \"\"\" checks if the point is inside the scene :param point:", "+ (pt_b.y() - pt_a.y()) ** 2) def pick_point(self, position): \"\"\" create a point", "no color (arena inside) to 255 occultation_mask[occultation_mask == 0] = 255 # 4)", "return result def is_in_scene(self, point): \"\"\" checks if the point is inside the", "in the paint mode, paint the event position self.save() self.draw(pos) def mouseReleaseEvent(self, event):", "stays pushed for button in self.color_buttons: if button.text() != text: button.setChecked(False) else: button.setChecked(True)", "QtGui.qRgba(255, 0, 0, 100) else: value = QtGui.qRgba(0, 0, 0, 0) # paint", "the polygons that are now changeable. :return: None \"\"\" # clear the canvas", "(all polygons are saved # as one step) self.backup = [] ########################## #", "0, 100) else: value = QtGui.qRgba(0, 0, 0, 0) # paint the area", "button.setChecked(False) else: button.setChecked(True) self.color = text def switch_mode(self): value = self.sender().text() if value", "store all progress bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt =", "0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint a point with a pen in", "background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint mode \"polygons\" or \"paint\"", "self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut", "is inside) # TODO: For some reason, color channels are full of 0,", "POLYGON MODE VARIABLES # ########################## # all independent points (they are not yet", "= QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider", "0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() #", "be a future part of a polygon :param position: :return: QGraphicsItem (from MyEllipse)", "in the polygons mode, try to pick one point precision = 20 ok", "finish_callback self.setMouseTracking(True) self.background = img self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene", "== \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self): \"\"\" remove all points", "arena\": value = QtGui.qRgba(255, 0, 0, 100) else: value = QtGui.qRgba(0, 0, 0,", "point.x() <= width and point.y() <= height: return True else: return False def", "[] # go through all saved points and recreate the polygons according to", "False def paint_polygon_(self, polygon, color): \"\"\" paints a polygon, when it's color and", "self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points = [] self.polygon_colors = [] def mouse_press_event(self,", "be drawn :return: None \"\"\" # change float to int (QPointF -> QPoint)", "# type MyEllipse[] # holds colors of polygons \"Red\" or \"Blue\" self.polygon_colors =", "progress bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image", "polygon if color == \"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0, 0, 100)", "dist < precision: print(\"Too close\") ok = False for points in self.polygon_points: for", "occultation is -> everything not blue is visible or outside of the arena)", "blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button", "go through all saved points and recreate the polygons according to the new", "TODO: occultation mask cannot be used at the same time. (they both share", "self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and", "color == \"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0, 0, 100) else: qc", "or \"Blue\" :return: None \"\"\" # setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image)", "button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color = text def switch_mode(self): value =", "precision: print(\"Too close\") ok = False for points in self.polygon_points: for pt in", "no other button stays pushed for button in self.color_buttons: if button.text() != text:", "= QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint", "# 3) set all pixels with no color (arena inside) to 255 occultation_mask[occultation_mask", "in point_items: self.scene.removeItem(point) # erase all independent points for point in self.point_items: self.scene.removeItem(point)", "= QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut self.action_clear", "red to 1 (temporary) arena_mask[arena_mask > 0] = 1 # 3) set all", "def draw(self, point): \"\"\" paint a point with a pen in paint mode", "img = self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def undo(self): if self.mode", "spot # 1) load BLUE channel (blue color shows where occultation is ->", "- self.pen_size/2, point.x() + self.pen_size/2): for j in range(point.y() - self.pen_size/2, point.y() +", "p.end() return result def is_in_scene(self, point): \"\"\" checks if the point is inside", "self.set_polygons_mode() else: # don't do anything if polygons mode is already active if", "bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0,", "(temporary) occultation_mask[occultation_mask > 0] = 1 # 3) set all pixels with no", "> 0 and j <= bg_height: try: self.paint_image.setPixel(i, j, value) except: pass #", "\"Paint mode\": # don't do anything if paint mode is already active if", "of 0, so they can't be used to create a mask. Mysteriously, #", "# if point is in the scene self.draw(point) # do nothing in \"polygons\"", "0, 0) # paint the area around the point position bg_height, bg_width =", "= 0 \"\"\" if self.finish_callback: # TODO: fix this so two different masks", "It is a separate method purely to save space :return: None \"\"\" ##########################", "(arena inside) to 255 arena_mask[arena_mask == 0] = 255 # 4) set all", "try to pick one point precision = 20 ok = True for pt", "use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and save it's", "TODO: label seems to be working well, uncomment later return arena_mask, None def", "qc = QtGui.QColor(255, 0, 0, 100) else: qc = QtGui.QColor(0, 0, 255, 100)", "TODO: add circles mode variables # temporary image to work with circles self.circles_image", "# TODO: label seems to be working well, uncomment later return arena_mask, None", "\"\"\" # setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() #", "widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button)", "self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img self.project = project self.view =", "images with paint image self.save() self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image() self.clear_circles_image()", "clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self):", "0, 0, 100) else: value = QtGui.qRgba(0, 0, 0, 0) # paint the", "too (all polygons are saved # as one step) self.backup = [] ##########################", "PyQt4 import QtGui, QtCore import cv2 import sys import math import numpy as", "the arena with red and use blue to mark possible\" \" hiding places.", "dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close2\") ok = False", "drawing self.mode = \"paint\" # adjust widgets displayed in the left panel self.poly_button.setVisible(False)", "= QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\")", "width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y() <= height:", "set all pixels that contain at least a little red to 1 (temporary)", "QtCore import cv2 import sys import math import numpy as np from core.project.project", "def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if self.mode == \"paint\": point =", "the point is inside the scene :param point: Qpoint or QPointF :return: True", "polygons mode is already active if self.mode == \"polygons\": return self.set_polygons_mode() else: #", "changeable. :return: None \"\"\" # clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = []", "be used at the same time. (they both share the same alpha channel)", ":return: None \"\"\" # clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points", "in the scene self.draw(point) # do nothing in \"polygons\" mode def get_event_pos(self, event):", "# holds colors of polygons \"Red\" or \"Blue\" self.polygon_colors = [] # type", "\"Blue\" self.polygon_colors = [] # type string[] # holds sets of all used", "method that returns the distance of two points (A, B) :param pt_a: Point", "def __init__(self, img, project, finish_callback=None): # TODO: add support for the original arena", "store last 10 QImages to support the \"undo\" function # undo button can", "with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image))", "the memory self.point_items = [] self.polygon_points = [] self.polygon_colors = [] # TODO:", "for el in self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw", "the main view and left panel with buttons self.make_gui() def switch_color(self): text =", "other already chosen point dist = self.get_distance(pt, pos) if dist < precision: print(\"Too", "self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png')", "# paint the polygon if color == \"Outside of\\nthe arena\": qc = QtGui.QColor(255,", "anything if polygons mode is already active if self.mode == \"circles\": return self.set_circles_mode()", "self.point_items = [] # type MyEllipse[] # holds colors of polygons \"Red\" or", "0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES # ########################## # TODO:", "10 QImages to support the \"undo\" function # undo button can only be", "> 0] = 1 # 3) set all pixels with no color (arena", "left panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome", ":return: True or False \"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x()", "self.mode = \"paint\" # adjust widgets displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True)", "\" hiding places. Unresolvable colors will be considered red.\") widget.layout().addWidget(label) # SWITCH button", "\"paint\" or \"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\" # store last 10", "pushed for button in self.color_buttons: if button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color", "widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button", "one step) self.backup = [] ########################## # PAINT MODE VARIABLES # ########################## self.pen_size", "are saved # as one step) self.backup = [] ########################## # PAINT MODE", "im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im, p)", "# get event position and calibrate to scene pos = self.get_event_pos(event) if not", "Mysteriously, # TODO: alpha channel seems to be working just fine. Arena mask", "the outside of the arena with red and use blue to mark possible\"", "the label to show current pen settings :return: None \"\"\" if self.mode ==", "in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the label to show current pen", "alpha channel seems to be working just fine. Arena mask is now working", "self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): #", "# check if polygon can be created if len(self.point_items) > 2: if self.DEBUG:", "pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple method that returns the distance", "# GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget = QtGui.QWidget()", "0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint a point with a pen", "%s\" % self.pen_size) def remove_items(self): \"\"\" remove all points from polygons mode from", "UNDO key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key", "arena is -> everything not red is inside) # TODO: For some reason,", "0 and i < bg_width and j > 0 and j <= bg_height:", "# use current pen color if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0,", "self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\"", "self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result def is_in_scene(self, point): \"\"\" checks if", "if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in the paint mode, paint", "is -> everything not blue is visible or outside of the arena) occultation_mask", "QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def", "'dita' from PyQt4 import QtGui, QtCore import cv2 import sys import math import", "= QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the polygon if color ==", "self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button)", "set_circles_mode(self): # join the temporary images with paint image self.save() self.refresh_image(self.merge_images()) # clean", "if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self): \"\"\" remove", "0, so they can't be used to create a mask. Mysteriously, # TODO:", "# print label(arena_mask, connectivity=2) # TODO: label seems to be working well, uncomment", "a polygon :param position: :return: QGraphicsItem (from MyEllipse) \"\"\" # picks and marks", "self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries to create a new polygon from", "add cleanup after circle drawing # cleanup after paint mode is not needed", "with paint image self.save() self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image() self.clear_circles_image() #", "sets of all used points. Each list corresponds to one polygon self.polygon_points =", "channel seems to be working just fine. Arena mask is now working with", "= value # refresh text in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the", "string[] # holds sets of all used points. Each list corresponds to one", "\"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget", "in image are formatted [R, G, B, A]. # To extract mask data,", "lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image = img", "polygons \"Red\" or \"Blue\" self.polygon_colors = [] # type string[] # holds sets", "recreate the polygons according to the new points' position i = 0 for", "0, 255, 100) elif self.color == \"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0,", "area around the point position bg_height, bg_width = self.background.shape[:2] for i in range(point.x()", "reset(self): \"\"\" clear everything and start over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image()", "memory self.point_items = [] self.polygon_points = [] self.polygon_colors = [] # cleanup after", "\"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): #", "data, only Red (0) and Blue (2) channels are needed. # Create arena", "self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items = [] return True else: if", "over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points = []", "QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) #", "widget.layout().addWidget(label) # SWITCH button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon", "self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES # ########################## # all independent points", "self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing", "gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img, project, finish_callback=None):", "point else: return False def save(self): \"\"\" Saves current image temporarily (to use", "and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the points (ellipses),", "make sure no other button stays pushed for button in self.color_buttons: if button.text()", "tries to create a new polygon from currently selected points (MyEllipses) :return: bool,", "considered red.\") widget.layout().addWidget(label) # SWITCH button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button", "self.pen_size/2, point.x() + self.pen_size/2): for j in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2):", "self.sender().text() if self.DEBUG: print((\"Setting color to %s\" % text)) # make sure no", "the widget. It is a separate method purely to save space :return: None", "add circles mode variables # temporary image to work with circles self.circles_image =", "polygon can be created if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete, drawing", "create a new polygon from currently selected points (MyEllipses) :return: bool, whether the", "polygon :param position: :return: QGraphicsItem (from MyEllipse) \"\"\" # picks and marks a", "for points in self.polygon_points: for pt in points: dist = self.get_distance(pt, pos) if", "point = self.get_event_pos(event) if point: # if point is in the scene self.draw(point)", "# as one step) self.backup = [] ########################## # PAINT MODE VARIABLES #", "= QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## #", "do anything if polygons mode is already active if self.mode == \"polygons\": return", "case \"Eraser\" was chosen as a color, switch it to blue if self.color", "for point in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def", "self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup)", "create the main view and left panel with buttons self.make_gui() def switch_color(self): text", "all the polygons that are now changeable. :return: None \"\"\" # clear the", "None def change_pen_size(self, value): \"\"\" change pen size :param value: new pen size", "if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete, drawing it\") # create the", "color (arena inside) to 255 arena_mask[arena_mask == 0] = 255 # 4) set", "or False \"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width", "shows where outside of the arena is -> everything not red is inside)", "position): \"\"\" create a point that the user has chosen to be a", "# ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop)", "as one step) self.backup = [] ########################## # PAINT MODE VARIABLES # ##########################", "MyEllipse[][] # temporary image to work with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0,", "!= text: button.setChecked(False) else: button.setChecked(True) self.color = text def switch_mode(self): value = self.sender().text()", "place to hide (it is visible) \"\"\" img = self.merge_images() bg_height, bg_width =", "self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0,", "not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus)", "be used to create a mask. Mysteriously, # TODO: alpha channel seems to", "DEBUG = True def __init__(self, img, project, finish_callback=None): # TODO: add support for", "circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = []", "image are formatted [R, G, B, A]. # To extract mask data, only", "blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button)", "points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse)", "cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500,", "# remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): #", "= QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text()", "= QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0,", "join the temporary images with paint image self.save() self.refresh_image(self.merge_images()) # clean the temporary", "switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True)", "to one polygon self.polygon_points = [] # type MyEllipse[][] # temporary image to", "= tmp_points def merge_images(self): \"\"\" merges the 3 images (paint, polygons and circles)", "arena_mask[arena_mask == 0] = 255 # 4) set all red pixels (value 1)", "distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y() - pt_a.y()) **", "QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__", "self.refresh_circles_image() def draw(self, point): \"\"\" paint a point with a pen in paint", "# SWITCH button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\")", "= QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image))", "self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image()", "connectivity=2) # TODO: label seems to be working well, uncomment later return arena_mask,", "arrays :return: tuple (arena_mask, occultation_mask) True in arena_masks means that the point is", "# 4) set all blue pixels (value 1) to 0 occultation_mask[occultation_mask == 1]", "= [] for point in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon,", "points and recreate the polygons according to the new points' position i =", "all points from polygons mode from the scene :return: \"\"\" # erase all", "[] tmp_points = [] # go through all saved points and recreate the", "= QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0,", "= QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) #", "\"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y()", "into one result :return: the final image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size", "the polygon if color == \"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0, 0,", "saved # as one step) self.backup = [] ########################## # PAINT MODE VARIABLES", "label(arena_mask, connectivity=2) # TODO: label seems to be working well, uncomment later return", "the area around the point position bg_height, bg_width = self.background.shape[:2] for i in", "temporarily (to use with \"undo()\" later) :return: \"\"\" # save last 10 images", "self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image))", "paint a point with a pen in paint mode :param point: point to", "= QtGui.qRgba(255, 0, 0, 100) else: value = QtGui.qRgba(0, 0, 0, 0) #", "mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint", "paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app =", "with no color (arena inside) to 255 occultation_mask[occultation_mask == 0] = 255 #", "= QtGui.QPolygonF() for el in self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(), el.y()))", "- clear the memory self.point_items = [] self.polygon_points = [] self.polygon_colors = []", "from polygons mode from the scene :return: \"\"\" # erase all points from", "the arena True in occultation_mask means that the point is NOT a place", "eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel()", "return point else: return False def save(self): \"\"\" Saves current image temporarily (to", "= QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex", "QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end()", "self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2) # TODO: label seems", "\"\"\" clear everything and start over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items", "(2) channels are needed. # Create arena mask: 0 - outside, 255 -", "position bg_height, bg_width = self.background.shape[:2] for i in range(point.x() - self.pen_size/2, point.x() +", "painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints", "don't do anything if polygons mode is already active if self.mode == \"polygons\":", "size :return: None \"\"\" # change pen size self.pen_size = value # refresh", "= self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color", "np from core.project.project import Project from gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse", "self.color = text def switch_mode(self): value = self.sender().text() if value == \"Paint mode\":", "that contain at least a little red to 1 (temporary) arena_mask[arena_mask > 0]", "widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50,", "- visible spot # 1) load BLUE channel (blue color shows where occultation", "# CIRCLES MODE VARIABLES # ########################## # TODO: add circles mode variables #", "(they both share the same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) #", "little blue to 1 (temporary) occultation_mask[occultation_mask > 0] = 1 # 3) set", "# cleanup after paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button", "########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) #", "some reason, color channels are full of 0, so they can't be used", "self.save() self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image() self.clear_circles_image() # clean after polygon", "purely to save space :return: None \"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout())", "= 20 ok = True for pt in self.point_items: # check if the", "300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the", "to work with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap", "# TODO: add circles mode variables # temporary image to work with circles", "pick at least 3 points\") return False def paint_polygon_(self, polygon, color): \"\"\" paints", "brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return", "QtGui.QBrush() # paint the polygon if color == \"Outside of\\nthe arena\": qc =", "= 255 # 4) set all blue pixels (value 1) to 0 occultation_mask[occultation_mask", "self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join", "self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to numpy arrays :return: tuple (arena_mask, occultation_mask)", "self.mode == \"paint\": # in the paint mode, paint the event position self.save()", "# store all the points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary points' storage", "QtGui.QColor(255, 0, 0, 100) else: qc = QtGui.QColor(0, 0, 255, 100) pen =", "import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img, project, finish_callback=None): #", "paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget", "self.clear_circles_image() # clean after polygon drawing # - remove all points and polygons", "bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size,", "if self.mode == \"polygons\": # in the polygons mode, try to pick one", "= self.get_event_pos(event) if point: # if point is in the scene self.draw(point) #", "only be pushed in paint mode, but affects polygon painting too (all polygons", "= self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def undo(self): if self.mode ==", "A :param pt_b: Point B :return: float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x())", "3 images (paint, polygons and circles) into one result :return: the final image", "cleanup after paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in", "polygons according to the new points' position i = 0 for points in", "in the scene return if self.mode == \"polygons\": # in the polygons mode,", "########################## # POLYGON MODE VARIABLES # ########################## # all independent points (they are", "np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels that contain at least a", "distance of two points (A, B) :param pt_a: Point A :param pt_b: Point", "= True def __init__(self, img, project, finish_callback=None): # TODO: add support for the", "polygon polygon = QtGui.QPolygonF() for el in self.point_items: # use all selected points", "MODE VARIABLES # ########################## self.pen_size = 30 # image to store all progress", "paint image self.save() self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image() self.clear_circles_image() # clean", "self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint a point with", "for pt in points: dist = self.get_distance(pt, pos) if dist < precision: print(\"Too", "self.draw(point) # do nothing in \"polygons\" mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint()", "any polygon) self.point_items = [] # type MyEllipse[] # holds colors of polygons", "VARIABLES # ########################## # all independent points (they are not yet part of", "> 10: self.backup.pop(0) def undo(self): if self.mode == \"paint\": lenght = len(self.backup) if", "None \"\"\" # setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush()", "position i = 0 for points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse =", "in self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon", "with alpha data, but # TODO: occultation mask cannot be used at the", "\"paint\": lenght = len(self.backup) if lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def", "= QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button)", "all independent points for point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything", "%s\" % text)) # make sure no other button stays pushed for button", "Point B :return: float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2 +", "= Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500, -500) ex.showMaximized() ex.setFocus() app.exec_() app.deleteLater()", "def clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def", "variables # temporary image to work with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0,", "polygon) self.point_items = [] # type MyEllipse[] # holds colors of polygons \"Red\"", "self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def", "# TODO: add support for the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__()", "load RED channel (red color shows where outside of the arena is ->", "# DRAW button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon)", "self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing # - remove all points and", "TODO: add cleanup after circle drawing self.mode = \"paint\" # adjust widgets displayed", "there are no erasers in polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was", "drawn :return: None \"\"\" # change float to int (QPointF -> QPoint) if", "self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points = [] # go through all saved", "True else: if self.DEBUG: print(\"Polygon is too small, pick at least 3 points\")", "# erase all independent points for point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\"", "ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries to create a new", "to 0 arena_mask[arena_mask == 1] = 0 # invert mask arena_mask = np.invert(arena_mask)", "def reset(self): \"\"\" clear everything and start over :return: None \"\"\" self.remove_items() self.clear_poly_image()", "mode \"polygons\" or \"paint\" or \"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\" #", "a future part of a polygon :param position: :return: QGraphicsItem (from MyEllipse) \"\"\"", "occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels that contain at least", "QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button", "channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels that contain", "for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts", "in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True)", "= \"Hiding\\nplaces\" # store last 10 QImages to support the \"undo\" function #", "self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0,", "color and position are known :param polygon: QPolygonF to be painted :param color:", "settings :return: None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size)", "all pixels with no color (arena inside) to 255 arena_mask[arena_mask == 0] =", "dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close\") ok = False", "def is_in_scene(self, point): \"\"\" checks if the point is inside the scene :param", "painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all", "== \"paint\": point = self.get_event_pos(event) if point: # if point is in the", "self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100) elif self.color == \"Outside", "self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0,", "QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon',", "img = self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr =", "left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True)", "self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ##########################", "later) :return: \"\"\" # save last 10 images img = self.paint_image.copy() self.backup.append(img) if", "and position are known :param polygon: QPolygonF to be painted :param color: \"Red\"", "QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label", "paints a polygon, when it's color and position are known :param polygon: QPolygonF", "mode is already active if self.mode == \"polygons\": return self.set_polygons_mode() else: # don't", "\"\"\" bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result", "self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ ==", "with no color (arena inside) to 255 arena_mask[arena_mask == 0] = 255 #", "\"circles\": return self.set_circles_mode() def set_paint_mode(self): # join the temporary images with paint image", "cleanup after circle drawing self.mode = \"paint\" # adjust widgets displayed in the", "None \"\"\" # change pen size self.pen_size = value # refresh text in", "def set_label_text(self): \"\"\" changes the label to show current pen settings :return: None", "self.refresh_poly_image() def clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image()", "point is INSIDE the arena True in occultation_mask means that the point is", "if self.mode == \"paint\": point = self.get_event_pos(event) if point: # if point is", "def mouse_press_event(self, event): # get event position and calibrate to scene pos =", "event): self.save() def mouse_moving(self, event): if self.mode == \"paint\": point = self.get_event_pos(event) if", "self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def undo(self): if self.mode == \"paint\":", "self.mode == \"paint\": return self.set_paint_mode() elif value == \"Polygon mode\": # don't do", "numpy arrays :return: tuple (arena_mask, occultation_mask) True in arena_masks means that the point", "For some reason, color channels are full of 0, so they can't be", "last 10 images img = self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def", "self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\")", "possible\" \" hiding places. Unresolvable colors will be considered red.\") widget.layout().addWidget(label) # SWITCH", "== 0] = 255 # 4) set all blue pixels (value 1) to", "size: %s\" % self.pen_size) def remove_items(self): \"\"\" remove all points from polygons mode", "print label(arena_mask, connectivity=2) # TODO: label seems to be working well, uncomment later", "of a polygon :param position: :return: QGraphicsItem (from MyEllipse) \"\"\" # picks and", "ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img, project, finish_callback=None): # TODO: add support", "self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self):", "image to store all progress bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height)", "as a color, switch it to blue if self.color == \"Eraser\": self.color =", "= QtGui.qRgba(0, 0, 0, 0) # paint the area around the point position", "remove all points and polygons self.remove_items() # - clear the memory self.point_items =", "= [] self.polygon_colors = [] # TODO: add cleanup after circle drawing self.mode", "INSIDE the arena True in occultation_mask means that the point is NOT a", "simple method that returns the distance of two points (A, B) :param pt_a:", "self.polygon_points = [] self.polygon_colors = [] # TODO: add cleanup after circle drawing", "set all blue pixels (value 1) to 0 occultation_mask[occultation_mask == 1] = 0", "the user has chosen to be a future part of a polygon :param", "if the point is inside the scene :param point: Qpoint or QPointF :return:", "is already active if self.mode == \"polygons\": return self.set_polygons_mode() else: # don't do", "from polygons for point_items in self.polygon_points: for point in point_items: self.scene.removeItem(point) # erase", "in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1", "seems to be working well, uncomment later return arena_mask, None def change_pen_size(self, value):", "position and calibrate to scene pos = self.get_event_pos(event) if not pos: # if", "self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn", "NOT a place to hide (it is visible) \"\"\" img = self.merge_images() bg_height,", "point precision = 20 ok = True for pt in self.point_items: # check", "drawing # cleanup after paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for", "original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background =", "update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the", "and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button)", "storage self.point_items = [] return True else: if self.DEBUG: print(\"Polygon is too small,", "import sys import math import numpy as np from core.project.project import Project from", "mode variables # temporary image to work with circles self.circles_image = QtGui.QImage(bg_size, fmt)", "QtCore.QPointF: point = point.toPoint() # use current pen color if self.color == \"Hiding\\nplaces\":", "pen in paint mode :param point: point to be drawn :return: None \"\"\"", "button.setChecked(True) self.color = text def switch_mode(self): value = self.sender().text() if value == \"Paint", "self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left", "repaints all the polygons that are now changeable. :return: None \"\"\" # clear", "clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self):", "** 2) def pick_point(self, position): \"\"\" create a point that the user has", "position: :return: QGraphicsItem (from MyEllipse) \"\"\" # picks and marks a point in", "to be painted :param color: \"Red\" or \"Blue\" :return: None \"\"\" # setup", "QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout())", "QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON", "polygon drawing # - remove all points and polygons self.remove_items() # - clear", "def make_gui(self): \"\"\" Creates the widget. It is a separate method purely to", "the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the polygon", "result :return: the final image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width,", "= QtGui.qRgba(0, 0, 255, 100) elif self.color == \"Outside of\\nthe arena\": value =", "switch_mode(self): value = self.sender().text() if value == \"Paint mode\": # don't do anything", "= self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img))", "polygons and circles) into one result :return: the final image \"\"\" bg_height, bg_width", "hide \"Eraser\" button, there are no erasers in polygons mode self.color_buttons[2].setVisible(False) # in", "is visible) \"\"\" img = self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr = img.constBits()", "invert mask arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion mask: 0 - occultation,", "red pixels (value 1) to 0 arena_mask[arena_mask == 1] = 0 # invert", "are formatted [R, G, B, A]. # To extract mask data, only Red", "if dist < precision: print(\"Too close\") ok = False for points in self.polygon_points:", "# remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): #", "100) else: qc = QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern)", "left panel with buttons self.make_gui() def switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting", "scene pos = self.get_event_pos(event) if not pos: # if pos isn't in the", "= self.get_event_pos(event) if not pos: # if pos isn't in the scene return", "occultation, 255 - visible spot # 1) load BLUE channel (blue color shows", "to pick one point precision = 20 ok = True for pt in", "polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ##########################", "self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\")", "both share the same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2)", "self.polygon_points: for point in point_items: self.scene.removeItem(point) # erase all independent points for point", "# 4) set all red pixels (value 1) to 0 arena_mask[arena_mask == 1]", "color to %s\" % text)) # make sure no other button stays pushed", "# adjust widgets displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button", "p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image)", "is now working with alpha data, but # TODO: occultation mask cannot be", "widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena", "print((\"Setting color to %s\" % text)) # make sure no other button stays", "red.\") widget.layout().addWidget(label) # SWITCH button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button =", "a mask. Mysteriously, # TODO: alpha channel seems to be working just fine.", "point.x() + self.pen_size/2): for j in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if", "= QtGui.QPolygonF() tmp_ellipse = [] for point in points: qpt = QtCore.QPointF(point.x(), point.y())", "polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y()))", "50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key", "0, self.circles_image) p.end() return result def is_in_scene(self, point): \"\"\" checks if the point", "any other already chosen point dist = self.get_distance(pt, pos) if dist < precision:", "all independent points (they are not yet part of any polygon) self.point_items =", "bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p", "bg_width = self.background.shape[:2] for i in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for", "remove_items(self): \"\"\" remove all points from polygons mode from the scene :return: \"\"\"", "paint the polygon if color == \"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0,", "True def __init__(self, img, project, finish_callback=None): # TODO: add support for the original", "self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False)", "of the arena is -> everything not red is inside) # TODO: For", "# im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im,", "\"\"\" # clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points = []", "but # TODO: occultation mask cannot be used at the same time. (they", "colors will be considered red.\") widget.layout().addWidget(label) # SWITCH button and key shortcut mode_switch_group", "no erasers in polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen as", "widget.layout().addWidget(circlemode_button) # color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button", "== \"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0, 0, 100) else: qc =", "point in point_items: self.scene.removeItem(point) # erase all independent points for point in self.point_items:", "RED channel (red color shows where outside of the arena is -> everything", "QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label)", "close2\") ok = False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in", "where occultation is -> everything not blue is visible or outside of the", "SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50)", "= 255 # 4) set all red pixels (value 1) to 0 arena_mask[arena_mask", "0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0,", "def change_pen_size(self, value): \"\"\" change pen size :param value: new pen size :return:", "used at the same time. (they both share the same alpha channel) arena_mask", "self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo", "[] # type MyEllipse[][] # temporary image to work with polygons self.poly_image =", "mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons", "temporary image to work with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0,", "self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" # TODO: add cleanup after", "button, there are no erasers in polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\"", "red is inside) # TODO: For some reason, color channels are full of", "# ########################## self.pen_size = 30 # image to store all progress bg_height, bg_width", "widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label =", "point: point to be drawn :return: None \"\"\" # change float to int", "else: button.setChecked(True) self.color = text def switch_mode(self): value = self.sender().text() if value ==", "points (MyEllipses) :return: bool, whether the polygon was drawn \"\"\" # check if", "QImages to support the \"undo\" function # undo button can only be pushed", "widget. It is a separate method purely to save space :return: None \"\"\"", "only Red (0) and Blue (2) channels are needed. # Create arena mask:", "= True for pt in self.point_items: # check if the clicked pos isn't", "point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for", "[] # cleanup after paint mode is not needed self.mode = \"circles\" self.poly_button.setVisible(False)", "text = self.sender().text() if self.DEBUG: print((\"Setting color to %s\" % text)) # make", "= QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\" merges the 3", "a point that the user has chosen to be a future part of", "== \"circles\": return self.set_circles_mode() def set_paint_mode(self): # join the temporary images with paint", "to save space :return: None \"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom)", "images img = self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def undo(self): if", ":return: None \"\"\" # change pen size self.pen_size = value # refresh text", "[] self.polygon_points = [] self.polygon_colors = [] # TODO: add cleanup after circle", "class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img, project, finish_callback=None): # TODO: add", "= cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500, -500) ex.showMaximized()", "= np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in image are formatted [R, G,", "\"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y() - pt_a.y()) ** 2)", "event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return False def save(self):", "QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) #", "= [] tmp_points = [] # go through all saved points and recreate", "self.polygon_points: for pt in points: dist = self.get_distance(pt, pos) if dist < precision:", "\"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0, 0, 100) else: value = QtGui.qRgba(0,", "brush = QtGui.QBrush() # paint the polygon if color == \"Outside of\\nthe arena\":", "one polygon self.polygon_points = [] # type MyEllipse[][] # temporary image to work", "self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self):", "arena_mask, None def change_pen_size(self, value): \"\"\" change pen size :param value: new pen", "> 2: if self.DEBUG: print(\"Polygon complete, drawing it\") # create the polygon polygon", "self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES # ########################## # all", "selected points (MyEllipses) :return: bool, whether the polygon was drawn \"\"\" # check", "all points and polygons self.remove_items() # - clear the memory self.point_items = []", "self.color_buttons: if button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color = text def switch_mode(self):", "self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and", "__author__ = 'dita' from PyQt4 import QtGui, QtCore import cv2 import sys import", "inside # 1) load RED channel (red color shows where outside of the", ":return: QGraphicsItem (from MyEllipse) \"\"\" # picks and marks a point in the", "True else: return False def make_gui(self): \"\"\" Creates the widget. It is a", "pen color if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100) elif", "(ellipses), too self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items = [] return True", "0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES # ##########################", "point.y() + self.pen_size/2): if i >= 0 and i < bg_width and j", "QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider =", "with a pen in paint mode :param point: point to be drawn :return:", "None \"\"\" # clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points =", "can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2)", "blue is visible or outside of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") #", "= img self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene)", "if value == \"Paint mode\": # don't do anything if paint mode is", "None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self):", "# CLEAR button and key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear)", "(pt_b.y() - pt_a.y()) ** 2) def pick_point(self, position): \"\"\" create a point that", "polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point", "inside) # TODO: For some reason, color channels are full of 0, so", "reason, color channels are full of 0, so they can't be used to", "future part of a polygon :param position: :return: QGraphicsItem (from MyEllipse) \"\"\" #", "are not yet part of any polygon) self.point_items = [] # type MyEllipse[]", "lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn lines", "# setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint", "use with \"undo()\" later) :return: \"\"\" # save last 10 images img =", "drawn \"\"\" # check if polygon can be created if len(self.point_items) > 2:", "import Project from gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import", "undo(self): if self.mode == \"paint\": lenght = len(self.backup) if lenght > 0: img", "affects polygon painting too (all polygons are saved # as one step) self.backup", "already active if self.mode == \"paint\": return self.set_paint_mode() elif value == \"Polygon mode\":", "self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there are no", "# store last 10 QImages to support the \"undo\" function # undo button", "occlusion mask: 0 - occultation, 255 - visible spot # 1) load BLUE", "save(self): \"\"\" Saves current image temporarily (to use with \"undo()\" later) :return: \"\"\"", "store the current paint mode \"polygons\" or \"paint\" or \"circles\" self.mode = \"\"", "j > 0 and j <= bg_height: try: self.paint_image.setPixel(i, j, value) except: pass", "TODO: add cleanup after circle drawing # cleanup after paint mode is not", "holds colors of polygons \"Red\" or \"Blue\" self.polygon_colors = [] # type string[]", "MyEllipse) \"\"\" # picks and marks a point in the polygon mode brush", "self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True)", "visible) \"\"\" img = self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount())", "the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(),", "at the same time. (they both share the same alpha channel) arena_mask =", "button stays pushed for button in self.color_buttons: if button.text() != text: button.setChecked(False) else:", ":return: float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y() -", "- inside # 1) load RED channel (red color shows where outside of", "contain at least a little red to 1 (temporary) arena_mask[arena_mask > 0] =", "mask arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion mask: 0 - occultation, 255", "in case \"Eraser\" was chosen as a color, switch it to blue if", "bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image =", "255, 100) elif self.color == \"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0, 0,", "the scene self.draw(point) # do nothing in \"polygons\" mode def get_event_pos(self, event): point", "# ########################## # TODO: add circles mode variables # temporary image to work", "value == \"Paint mode\": # don't do anything if paint mode is already", "means that the point is NOT a place to hide (it is visible)", ":return: None \"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel", "inside) to 255 arena_mask[arena_mask == 0] = 255 # 4) set all red", "<= height: return True else: return False def make_gui(self): \"\"\" Creates the widget.", "is in the scene self.draw(point) # do nothing in \"polygons\" mode def get_event_pos(self,", "\"\"\" # change float to int (QPointF -> QPoint) if type(point) == QtCore.QPointF:", "polygon was drawn \"\"\" # check if polygon can be created if len(self.point_items)", "\"\"\" Creates the widget. It is a separate method purely to save space", "point): \"\"\" checks if the point is inside the scene :param point: Qpoint", "event position and calibrate to scene pos = self.get_event_pos(event) if not pos: #", "pos isn't too close to any other already chosen point dist = self.get_distance(pt,", "\"\"\" # erase all points from polygons for point_items in self.polygon_points: for point", "no color (arena inside) to 255 arena_mask[arena_mask == 0] = 255 # 4)", "converts image to numpy arrays :return: tuple (arena_mask, occultation_mask) True in arena_masks means", "all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and save it's color", "= [] # type MyEllipse[] # holds colors of polygons \"Red\" or \"Blue\"", "True for pt in self.point_items: # check if the clicked pos isn't too", "np.invert(arena_mask) \"\"\" # Create occlusion mask: 0 - occultation, 255 - visible spot", "mouse_press_event(self, event): # get event position and calibrate to scene pos = self.get_event_pos(event)", "mouse_moving(self, event): if self.mode == \"paint\": point = self.get_event_pos(event) if point: # if", "polygon: QPolygonF to be painted :param color: \"Red\" or \"Blue\" :return: None \"\"\"", "in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\"", "2) set all pixels that contain at least a little red to 1", "arena_masks means that the point is INSIDE the arena True in occultation_mask means", "# clean the temporary images self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing #", "0, 0, 0) # paint the area around the point position bg_height, bg_width", "erase all independent points for point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear", "value = QtGui.qRgba(255, 0, 0, 100) else: value = QtGui.qRgba(0, 0, 0, 0)", "panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to", "polygons for point_items in self.polygon_points: for point in point_items: self.scene.removeItem(point) # erase all", "button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image", "= [] return True else: if self.DEBUG: print(\"Polygon is too small, pick at", "anything if paint mode is already active if self.mode == \"paint\": return self.set_paint_mode()", "already active if self.mode == \"polygons\": return self.set_polygons_mode() else: # don't do anything", "self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the polygons that are now changeable. :return:", "= QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter()", "all red pixels (value 1) to 0 arena_mask[arena_mask == 1] = 0 #", "fine. Arena mask is now working with alpha data, but # TODO: occultation", "0)) self.refresh_poly_image() def clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0))", "scene :return: \"\"\" # erase all points from polygons for point_items in self.polygon_points:", "return True else: return False def make_gui(self): \"\"\" Creates the widget. It is", "polygons mode, try to pick one point precision = 20 ok = True", "widgets displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons:", "(A, B) :param pt_a: Point A :param pt_b: Point B :return: float distance", "= MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) #", "remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\"", "-> QPoint) if type(point) == QtCore.QPointF: point = point.toPoint() # use current pen", "created if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete, drawing it\") # create", "color shows where outside of the arena is -> everything not red is", "editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img self.project", "draw the polygon and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all", "== \"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0, 0, 100) else: value =", "QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image() def", "widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget", "occultation_mask) True in arena_masks means that the point is INSIDE the arena True", "if dist < precision: print(\"Too close2\") ok = False if ok: self.point_items.append(self.pick_point(pos)) elif", "to be drawn :return: None \"\"\" # change float to int (QPointF ->", "self.color = \"Hiding\\nplaces\" # store last 10 QImages to support the \"undo\" function", "self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False)", "p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result def", "be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2) #", "def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return False", "type MyEllipse[] # holds colors of polygons \"Red\" or \"Blue\" self.polygon_colors = []", "and j <= bg_height: try: self.paint_image.setPixel(i, j, value) except: pass # set new", "if polygons mode is already active if self.mode == \"circles\": return self.set_circles_mode() def", "circles mode variables # temporary image to work with circles self.circles_image = QtGui.QImage(bg_size,", "points in self.polygon_points: for pt in points: dist = self.get_distance(pt, pos) if dist", "qc = QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen)", "QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW", "self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result def is_in_scene(self, point):", "the polygon polygon = QtGui.QPolygonF() for el in self.point_items: # use all selected", "that the point is INSIDE the arena True in occultation_mask means that the", "now changeable. :return: None \"\"\" # clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses =", "all blue pixels (value 1) to 0 occultation_mask[occultation_mask == 1] = 0 \"\"\"", "not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) # hide \"Eraser\"", "painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the polygon if color == \"Outside of\\nthe", "pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\" merges the", "refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the polygons that are", "left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget", "is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) # hide", "value) except: pass # set new image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a,", "label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the outside of the arena with red", "self.view.setMouseTracking(True) # store the current paint mode \"polygons\" or \"paint\" or \"circles\" self.mode", "in points: dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close2\") ok", "2) set all pixels that contain at least a little blue to 1", "drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint a", "self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## #", "QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\" merges the 3 images", "arena editor! Paint the outside of the arena with red and use blue", "least a little blue to 1 (temporary) occultation_mask[occultation_mask > 0] = 1 #", "tmp_ellipses = [] tmp_points = [] # go through all saved points and", "0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES # ########################## #", "def set_paint_mode(self): # join the temporary images with paint image self.save() self.refresh_image(self.merge_images()) #", ":param point: point to be drawn :return: None \"\"\" # change float to", "occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2) # TODO: label seems to", "area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete", "\"\" self.color = \"Hiding\\nplaces\" # store last 10 QImages to support the \"undo\"", "image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple method that returns", "(from MyEllipse) \"\"\" # picks and marks a point in the polygon mode", "= QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button)", "images self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing # - remove all points", "TODO: alpha channel seems to be working just fine. Arena mask is now", "# paint the area around the point position bg_height, bg_width = self.background.shape[:2] for", "def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap)", "mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher", "in self.polygon_points: for pt in points: dist = self.get_distance(pt, pos) if dist <", "polygons are saved # as one step) self.backup = [] ########################## # PAINT", "blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\")", "set left panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True)", "a polygon, when it's color and position are known :param polygon: QPolygonF to", "el.y())) # draw the polygon and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) #", "0 arena_mask[arena_mask == 1] = 0 # invert mask arena_mask = np.invert(arena_mask) \"\"\"", "all the points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items =", "point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything and start over :return:", "after paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons:", "button in self.color_buttons: if button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color = text", "\"\"\" # change pen size self.pen_size = value # refresh text in QLabel", "button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button =", "self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset)", "(value 1) to 0 occultation_mask[occultation_mask == 1] = 0 \"\"\" if self.finish_callback: #", "QPolygonF to be painted :param color: \"Red\" or \"Blue\" :return: None \"\"\" #", "tmp_ellipse = [] for point in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt))", "button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode)", "PAINT MODE VARIABLES # ########################## self.pen_size = 30 # image to store all", "cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500, -500) ex.showMaximized() ex.setFocus()", "new image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple method that", "tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos))", "if the clicked pos isn't too close to any other already chosen point", "chosen point dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close\") ok", "len(self.backup) if lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image", "0) # paint the area around the point position bg_height, bg_width = self.background.shape[:2]", "to mark possible\" \" hiding places. Unresolvable colors will be considered red.\") widget.layout().addWidget(label)", "if self.finish_callback: # TODO: fix this so two different masks can be used", "try: self.paint_image.setPixel(i, j, value) except: pass # set new image and pixmap self.refresh_image(self.paint_image)", "self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def", "color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\")", "mask is now working with alpha data, but # TODO: occultation mask cannot", "self.point_items = [] self.polygon_points = [] self.polygon_colors = [] # TODO: add cleanup", "self.color) self.polygon_colors.append(self.color) # store all the points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary", "drawing # - remove all points and polygons self.remove_items() # - clear the", "color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button =", "hide (it is visible) \"\"\" img = self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr", "self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image)", "np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in image are formatted [R, G, B,", "0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0))", "type(point) == QtCore.QPointF: point = point.toPoint() # use current pen color if self.color", "image self.save() self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image() self.clear_circles_image() # clean after", "self.point_items = [] self.polygon_points = [] self.polygon_colors = [] # cleanup after paint", "and start over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points", "########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget =", "self.sender().text() if value == \"Paint mode\": # don't do anything if paint mode", "0 - outside, 255 - inside # 1) load RED channel (red color", "if self.mode == \"paint\": lenght = len(self.backup) if lenght > 0: img =", "color if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100) elif self.color", "1 (temporary) arena_mask[arena_mask > 0] = 1 # 3) set all pixels with", "button in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there are no erasers in", "when it's color and position are known :param polygon: QPolygonF to be painted", "image to numpy arrays :return: tuple (arena_mask, occultation_mask) True in arena_masks means that", "last 10 QImages to support the \"undo\" function # undo button can only", "a point in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse =", "are now changeable. :return: None \"\"\" # clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses", "the temporary images self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing # - remove", "for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode", "points from polygons mode from the scene :return: \"\"\" # erase all points", "from the scene :return: \"\"\" # erase all points from polygons for point_items", "alpha data, but # TODO: occultation mask cannot be used at the same", "position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries to create a new polygon", "if pos isn't in the scene return if self.mode == \"polygons\": # in", "paint_polygon_(self, polygon, color): \"\"\" paints a polygon, when it's color and position are", "function # undo button can only be pushed in paint mode, but affects", "in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to", "None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points = [] self.polygon_colors =", "bg_width and j > 0 and j <= bg_height: try: self.paint_image.setPixel(i, j, value)", "self.DEBUG: print(\"Polygon complete, drawing it\") # create the polygon polygon = QtGui.QPolygonF() for", "all progress bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32", "== \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self):", "switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting color to %s\" % text)) #", "all saved points and recreate the polygons according to the new points' position", "self.point_items = [] self.polygon_points = [] self.polygon_colors = [] def mouse_press_event(self, event): #", "if self.mode == \"paint\": return self.set_paint_mode() elif value == \"Polygon mode\": # don't", "self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button", "False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in the paint mode,", "= \"paint\" # adjust widgets displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True)", "VARIABLES # ########################## # TODO: add circles mode variables # temporary image to", "point = point.toPoint() # use current pen color if self.color == \"Hiding\\nplaces\": value", "########################## self.pen_size = 30 # image to store all progress bg_height, bg_width =", "= 0 # invert mask arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion mask:", "(red color shows where outside of the arena is -> everything not red", "== \"paint\": # in the paint mode, paint the event position self.save() self.draw(pos)", "the current paint mode \"polygons\" or \"paint\" or \"circles\" self.mode = \"\" self.color", "float to int (QPointF -> QPoint) if type(point) == QtCore.QPointF: point = point.toPoint()", "if paint mode is already active if self.mode == \"paint\": return self.set_paint_mode() elif", "0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap", "self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" # TODO: add cleanup after circle drawing", "from gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView class", "chosen to be a future part of a polygon :param position: :return: QGraphicsItem", "1] = 0 # invert mask arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion", "= QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image()", "work with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap =", "bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result =", "the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background", "use blue to mark possible\" \" hiding places. Unresolvable colors will be considered", "<= width and point.y() <= height: return True else: return False def make_gui(self):", "pt in points: dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close2\")", "of two points (A, B) :param pt_a: Point A :param pt_b: Point B", "= [] self.polygon_points = [] self.polygon_colors = [] # TODO: add cleanup after", "the clicked pos isn't too close to any other already chosen point dist", "and point.y() <= height: return True else: return False def make_gui(self): \"\"\" Creates", "else: qc = QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush)", "color channels are full of 0, so they can't be used to create", "alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels that", "0 - occultation, 255 - visible spot # 1) load BLUE channel (blue", "paint mode :param point: point to be drawn :return: None \"\"\" # change", "qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points", "in self.point_items: # check if the clicked pos isn't too close to any", "DRAW button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button", "set_paint_mode(self): # join the temporary images with paint image self.save() self.refresh_image(self.merge_images()) # clean", "working well, uncomment later return arena_mask, None def change_pen_size(self, value): \"\"\" change pen", "for the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True)", "= text def switch_mode(self): value = self.sender().text() if value == \"Paint mode\": #", "pass # set new image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\"", "polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color)", "widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget)", "to int (QPointF -> QPoint) if type(point) == QtCore.QPointF: point = point.toPoint() #", "if not pos: # if pos isn't in the scene return if self.mode", "def set_circles_mode(self): # join the temporary images with paint image self.save() self.refresh_image(self.merge_images()) #", "(to use with \"undo()\" later) :return: \"\"\" # save last 10 images img", ":param position: :return: QGraphicsItem (from MyEllipse) \"\"\" # picks and marks a point", "the paint mode, paint the event position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save()", "# TODO: For some reason, color channels are full of 0, so they", "independent points (they are not yet part of any polygon) self.point_items = []", "ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in the paint mode, paint the", "= len(self.backup) if lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img):", "# ########################## # all independent points (they are not yet part of any", "# create the polygon polygon = QtGui.QPolygonF() for el in self.point_items: # use", "def remove_items(self): \"\"\" remove all points from polygons mode from the scene :return:", "\"Red\" or \"Blue\" :return: None \"\"\" # setup the painter painter = QtGui.QPainter()", "mode is not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in", "the scene :param point: Qpoint or QPointF :return: True or False \"\"\" height,", "nothing in \"polygons\" mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return", "else: return False def make_gui(self): \"\"\" Creates the widget. It is a separate", "== \"paint\": lenght = len(self.backup) if lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img)", "[] self.polygon_points = [] self.polygon_colors = [] def mouse_press_event(self, event): # get event", "clear the memory self.point_items = [] self.polygon_points = [] self.polygon_colors = [] #", "be working just fine. Arena mask is now working with alpha data, but", "the polygon was drawn \"\"\" # check if polygon can be created if", "pt in self.point_items: # check if the clicked pos isn't too close to", "\"\"\" remove all points from polygons mode from the scene :return: \"\"\" #", "self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z))", "if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im =", "for point in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i", "if self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self): # join the temporary images", "least 3 points\") return False def paint_polygon_(self, polygon, color): \"\"\" paints a polygon,", "B) :param pt_a: Point A :param pt_b: Point B :return: float distance \"\"\"", "save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the points (ellipses), too", "to create a new polygon from currently selected points (MyEllipses) :return: bool, whether", "the distance of two points (A, B) :param pt_a: Point A :param pt_b:", "tmp_ellipses for point in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points", "= [] self.polygon_points = [] self.polygon_colors = [] def mouse_press_event(self, event): # get", "self.save() def mouse_moving(self, event): if self.mode == \"paint\": point = self.get_event_pos(event) if point:", "import MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self,", "return if self.mode == \"polygons\": # in the polygons mode, try to pick", "def pick_point(self, position): \"\"\" create a point that the user has chosen to", "= MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries to", "# PAINT MODE VARIABLES # ########################## self.pen_size = 30 # image to store", "= [] self.polygon_colors = [] # cleanup after paint mode is not needed", "polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\")", "shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key", "= self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and left panel with buttons self.make_gui()", "= [] # type string[] # holds sets of all used points. Each", "and point.x() <= width and point.y() <= height: return True else: return False", "core.project.project import Project from gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view", "after paint mode is not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for", "arena_mask[arena_mask > 0] = 1 # 3) set all pixels with no color", "and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple method that returns the", "can only be pushed in paint mode, but affects polygon painting too (all", "if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False)", "255 - visible spot # 1) load BLUE channel (blue color shows where", "= self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height,", "images (paint, polygons and circles) into one result :return: the final image \"\"\"", "mode, paint the event position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self,", "255 arena_mask[arena_mask == 0] = 255 # 4) set all red pixels (value", "\"__main__\": app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p =", "= QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button)", "+ self.pen_size/2): if i >= 0 and i < bg_width and j >", "was chosen as a color, switch it to blue if self.color == \"Eraser\":", "= point.toPoint() # use current pen color if self.color == \"Hiding\\nplaces\": value =", "# POLYGON MODE VARIABLES # ########################## # all independent points (they are not", "\"\"\" img = self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr", "[] # type string[] # holds sets of all used points. Each list", ":param polygon: QPolygonF to be painted :param color: \"Red\" or \"Blue\" :return: None", "self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary images with paint image self.save()", "self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img self.project = project self.view = MyView(update_callback_move=self.mouse_moving,", "hiding places. Unresolvable colors will be considered red.\") widget.layout().addWidget(label) # SWITCH button and", "self.pen_size/2): if i >= 0 and i < bg_width and j > 0", "inside the scene :param point: Qpoint or QPointF :return: True or False \"\"\"", "# if pos isn't in the scene return if self.mode == \"polygons\": #", "MODE VARIABLES # ########################## # all independent points (they are not yet part", "3 points\") return False def paint_polygon_(self, polygon, color): \"\"\" paints a polygon, when", "store all the points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items", "text in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the label to show current", "self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to numpy", "self.polygon_colors = [] # cleanup after paint mode is not needed self.mode =", ":param point: Qpoint or QPointF :return: True or False \"\"\" height, width =", "color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True)", "0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES # ########################## #", "points (A, B) :param pt_a: Point A :param pt_b: Point B :return: float", "255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\"", "self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in self.point_items: pos", "through all saved points and recreate the polygons according to the new points'", "QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the polygon if color == \"Outside", "points (they are not yet part of any polygon) self.point_items = [] #", "QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0))", "self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self): \"\"\" remove all", "change float to int (QPointF -> QPoint) if type(point) == QtCore.QPointF: point =", "and marks a point in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))", "in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush)", "= QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0,", "point to be drawn :return: None \"\"\" # change float to int (QPointF", "different masks can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print", "for point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything and start over", "print(\"Polygon is too small, pick at least 3 points\") return False def paint_polygon_(self,", "return self.set_circles_mode() def set_paint_mode(self): # join the temporary images with paint image self.save()", "for point in point_items: self.scene.removeItem(point) # erase all independent points for point in", "(arena_mask, occultation_mask) True in arena_masks means that the point is INSIDE the arena", "all pixels that contain at least a little blue to 1 (temporary) occultation_mask[occultation_mask", "drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove all drawn", "polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut self.action_clear = QtGui.QAction('clear',", "self.scene.removeItem(point) # erase all independent points for point in self.point_items: self.scene.removeItem(point) def reset(self):", "QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the label to show current pen settings", "point with a pen in paint mode :param point: point to be drawn", "mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color", "color shows where occultation is -> everything not blue is visible or outside", "point_items: self.scene.removeItem(point) # erase all independent points for point in self.point_items: self.scene.removeItem(point) def", "label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the outside of the", "in arena_masks means that the point is INSIDE the arena True in occultation_mask", "corresponds to one polygon self.polygon_points = [] # type MyEllipse[][] # temporary image", "work with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap =", "temporary image to work with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0,", "Red (0) and Blue (2) channels are needed. # Create arena mask: 0", "mask. Mysteriously, # TODO: alpha channel seems to be working just fine. Arena", "else: # print label(arena_mask, connectivity=2) # TODO: label seems to be working well,", "import math import numpy as np from core.project.project import Project from gui.img_controls import", "in self.color_buttons: if button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color = text def", "= QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the outside of the arena", "D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut self.action_clear = QtGui.QAction('clear', self)", "if type(point) == QtCore.QPointF: point = point.toPoint() # use current pen color if", "True in arena_masks means that the point is INSIDE the arena True in", "gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog):", "= \"\" self.color = \"Hiding\\nplaces\" # store last 10 QImages to support the", "= \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False)", "= QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset)", "arena\": qc = QtGui.QColor(255, 0, 0, 100) else: qc = QtGui.QColor(0, 0, 255,", "for button in self.color_buttons: if button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color =", "paint mode is not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button", "working just fine. Arena mask is now working with alpha data, but #", "\"\"\" tries to create a new polygon from currently selected points (MyEllipses) :return:", "the scene :return: \"\"\" # erase all points from polygons for point_items in", "pick_point(self, position): \"\"\" create a point that the user has chosen to be", "# clean after polygon drawing # - remove all points and polygons self.remove_items()", "self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" # TODO: add", "everything and start over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = []", "if self.DEBUG: print(\"Polygon is too small, pick at least 3 points\") return False", "self.polygon_points = [] self.polygon_colors = [] def mouse_press_event(self, event): # get event position", "False def save(self): \"\"\" Saves current image temporarily (to use with \"undo()\" later)", "yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40,", "active if self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self): # join the temporary", "remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove", "self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap)", "QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image)", "# join the temporary images with paint image self.save() self.refresh_image(self.merge_images()) # clean the", "Create arena mask: 0 - outside, 255 - inside # 1) load RED", "mask: 0 - occultation, 255 - visible spot # 1) load BLUE channel", "self.scene.removeItem(point) def reset(self): \"\"\" clear everything and start over :return: None \"\"\" self.remove_items()", "paint the event position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event):", "[] # TODO: add cleanup after circle drawing self.mode = \"paint\" # adjust", "[] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe", "button and key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button =", "4) # Color values in image are formatted [R, G, B, A]. #", "img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in image are", "undo button can only be pushed in paint mode, but affects polygon painting", "QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size)", "(circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img self.project =", "polygon = QtGui.QPolygonF() tmp_ellipse = [] for point in points: qpt = QtCore.QPointF(point.x(),", "pt_a: Point A :param pt_b: Point B :return: float distance \"\"\" return math.sqrt((pt_b.x()", "QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button)", "bg_width, 4) # Color values in image are formatted [R, G, B, A].", "self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def", "is too small, pick at least 3 points\") return False def paint_polygon_(self, polygon,", "contain at least a little blue to 1 (temporary) occultation_mask[occultation_mask > 0] =", "widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the outside", "3) set all pixels with no color (arena inside) to 255 occultation_mask[occultation_mask ==", "= QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color)", "data, but # TODO: occultation mask cannot be used at the same time.", "with \"undo()\" later) :return: \"\"\" # save last 10 images img = self.paint_image.copy()", "polygon, color): \"\"\" paints a polygon, when it's color and position are known", ":return: None \"\"\" # change float to int (QPointF -> QPoint) if type(point)", "don't do anything if polygons mode is already active if self.mode == \"circles\":", "# make sure no other button stays pushed for button in self.color_buttons: if", "\"polygons\": return self.set_polygons_mode() else: # don't do anything if polygons mode is already", "ok = True for pt in self.point_items: # check if the clicked pos", "= project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image", "saved points and recreate the polygons according to the new points' position i", "paint the area around the point position bg_height, bg_width = self.background.shape[:2] for i", "self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key", "fix this so two different masks can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask,", "self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points = [] self.polygon_colors = [] def", "make_gui(self): \"\"\" Creates the widget. It is a separate method purely to save", "self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and left panel with buttons", "not blue is visible or outside of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\")", "image temporarily (to use with \"undo()\" later) :return: \"\"\" # save last 10", "\"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points = [] self.polygon_colors = []", "if point: # if point is in the scene self.draw(point) # do nothing", "mode from the scene :return: \"\"\" # erase all points from polygons for", "100) elif self.color == \"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0, 0, 100)", "result def is_in_scene(self, point): \"\"\" checks if the point is inside the scene", "i < bg_width and j > 0 and j <= bg_height: try: self.paint_image.setPixel(i,", "chosen as a color, switch it to blue if self.color == \"Eraser\": self.color", "active if self.mode == \"polygons\": return self.set_polygons_mode() else: # don't do anything if", "\"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True)", "cv2 import sys import math import numpy as np from core.project.project import Project", "a new polygon from currently selected points (MyEllipses) :return: bool, whether the polygon", "or \"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\" # store last 10 QImages", "is NOT a place to hide (it is visible) \"\"\" img = self.merge_images()", "arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels that contain at", "self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y() <= height: return True else: return", "# all independent points (they are not yet part of any polygon) self.point_items", "self.mode = \"\" self.color = \"Hiding\\nplaces\" # store last 10 QImages to support", "= QtGui.QBrush() # paint the polygon if color == \"Outside of\\nthe arena\": qc", "at least 3 points\") return False def paint_polygon_(self, polygon, color): \"\"\" paints a", "bg_height, bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4)", ":return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points = [] self.polygon_colors", "ok = False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in the", "separate method purely to save space :return: None \"\"\" ########################## # GUI #", "value # refresh text in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the label", "= self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0))", "########################## # all independent points (they are not yet part of any polygon)", "according to the new points' position i = 0 for points in self.polygon_points:", "paint mode, paint the event position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def", ":param color: \"Red\" or \"Blue\" :return: None \"\"\" # setup the painter painter", "\"\"\" # Create occlusion mask: 0 - occultation, 255 - visible spot #", "# type MyEllipse[][] # temporary image to work with polygons self.poly_image = QtGui.QImage(bg_size,", "ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in", "self.polygon_points = tmp_ellipses for point in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items", "def popup(self): \"\"\" converts image to numpy arrays :return: tuple (arena_mask, occultation_mask) True", "outside, 255 - inside # 1) load RED channel (red color shows where", "if polygon can be created if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete,", "QtGui, QtCore import cv2 import sys import math import numpy as np from", "point is inside the scene :param point: Qpoint or QPointF :return: True or", "False def make_gui(self): \"\"\" Creates the widget. It is a separate method purely", "that contain at least a little blue to 1 (temporary) occultation_mask[occultation_mask > 0]", "self.setMouseTracking(True) self.background = img self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene =", "clean the temporary images self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing # -", "self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background", "mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if self.mode == \"paint\": point = self.get_event_pos(event)", "buttons self.make_gui() def switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting color to %s\"", "self.get_distance(pt, pos) if dist < precision: print(\"Too close\") ok = False for points", "all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint", "# holds sets of all used points. Each list corresponds to one polygon", "pixels (value 1) to 0 arena_mask[arena_mask == 1] = 0 # invert mask", "widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label", "least a little red to 1 (temporary) arena_mask[arena_mask > 0] = 1 #", "pen size :return: None \"\"\" # change pen size self.pen_size = value #", "part of a polygon :param position: :return: QGraphicsItem (from MyEllipse) \"\"\" # picks", "self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported", "< precision: print(\"Too close\") ok = False for points in self.polygon_points: for pt", "True or False \"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <=", "# TODO: occultation mask cannot be used at the same time. (they both", "= [] # go through all saved points and recreate the polygons according", "el in self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the", "= [] self.polygon_colors = [] def mouse_press_event(self, event): # get event position and", "self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" # TODO: add cleanup", "def set_polygons_mode(self): self.mode = \"polygons\" # TODO: add cleanup after circle drawing #", "all pixels with no color (arena inside) to 255 occultation_mask[occultation_mask == 0] =", "gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def", "elif self.mode == \"paint\": # in the paint mode, paint the event position", "that are now changeable. :return: None \"\"\" # clear the canvas self.remove_items() self.clear_poly_image()", "label seems to be working well, uncomment later return arena_mask, None def change_pen_size(self,", "temporary images self.clear_poly_image() self.clear_circles_image() # clean after polygon drawing # - remove all", "now working with alpha data, but # TODO: occultation mask cannot be used", ":return: None \"\"\" # setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush =", "== QtCore.QPointF: point = point.toPoint() # use current pen color if self.color ==", "= self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all", "self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary images with paint image", "points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items = [] return", "1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in self.point_items: pos = QtCore.QPoint(point.x(), point.y())", "one point precision = 20 ok = True for pt in self.point_items: #", "= False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\": # in the paint", "= self.get_distance(pt, pos) if dist < precision: print(\"Too close2\") ok = False if", "formatted [R, G, B, A]. # To extract mask data, only Red (0)", "self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES # ########################## # TODO: add", "or outside of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all", "red and use blue to mark possible\" \" hiding places. Unresolvable colors will", "ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries", "0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0,", "1) to 0 occultation_mask[occultation_mask == 1] = 0 \"\"\" if self.finish_callback: # TODO:", "all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove all", "return ellipse def paint_polygon(self): \"\"\" tries to create a new polygon from currently", "a separate method purely to save space :return: None \"\"\" ########################## # GUI", "with red and use blue to mark possible\" \" hiding places. Unresolvable colors", "Unresolvable colors will be considered red.\") widget.layout().addWidget(label) # SWITCH button and key shortcut", "j in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if i >= 0 and", "########################## # CIRCLES MODE VARIABLES # ########################## # TODO: add circles mode variables", "- remove all points and polygons self.remove_items() # - clear the memory self.point_items", "A]. # To extract mask data, only Red (0) and Blue (2) channels", "tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in", "len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete, drawing it\") # create the polygon", "self.circles_image) p.end() return result def is_in_scene(self, point): \"\"\" checks if the point is", "or QPointF :return: True or False \"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point)", "self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0,", "np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels that contain at least a little", "\"paint\": # in the paint mode, paint the event position self.save() self.draw(pos) def", "painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the polygon if color", "a little blue to 1 (temporary) occultation_mask[occultation_mask > 0] = 1 # 3)", "arena mask: 0 - outside, 255 - inside # 1) load RED channel", "0] = 1 # 3) set all pixels with no color (arena inside)", "return math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y() - pt_a.y()) ** 2) def", "= np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels that contain at least a", "is already active if self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self): # join", "255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh", "be working well, uncomment later return arena_mask, None def change_pen_size(self, value): \"\"\" change", "# clear temporary points' storage self.point_items = [] return True else: if self.DEBUG:", "else: # don't do anything if polygons mode is already active if self.mode", "self.clear_poly_image() tmp_ellipses = [] tmp_points = [] # go through all saved points", "= QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse", "p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result def is_in_scene(self, point): \"\"\"", "self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary images with paint image self.save() self.refresh_image(self.merge_images())", "1) load BLUE channel (blue color shows where occultation is -> everything not", "to be working just fine. Arena mask is now working with alpha data,", "[] def mouse_press_event(self, event): # get event position and calibrate to scene pos", "Paint the outside of the arena with red and use blue to mark", "are no erasers in polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen", "current paint mode \"polygons\" or \"paint\" or \"circles\" self.mode = \"\" self.color =", "0] = 255 # 4) set all red pixels (value 1) to 0", "for pt in self.point_items: # check if the clicked pos isn't too close", "- pt_a.x()) ** 2 + (pt_b.y() - pt_a.y()) ** 2) def pick_point(self, position):", "0, 0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image)", "= self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES # ########################## # TODO: add circles", "used to create a mask. Mysteriously, # TODO: alpha channel seems to be", "= self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt)", "\"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\" # store last 10 QImages to", "self.get_event_pos(event) if point: # if point is in the scene self.draw(point) # do", "point in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i +=", "QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button)", "the point is INSIDE the arena True in occultation_mask means that the point", "value: new pen size :return: None \"\"\" # change pen size self.pen_size =", "QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button)", "# clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points = [] #", "self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo)", "the 3 images (paint, polygons and circles) into one result :return: the final", "else: return False def save(self): \"\"\" Saves current image temporarily (to use with", "point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\" merges the 3 images (paint,", "# - remove all points and polygons self.remove_items() # - clear the memory", "return False def paint_polygon_(self, polygon, color): \"\"\" paints a polygon, when it's color", "for point_items in self.polygon_points: for point in point_items: self.scene.removeItem(point) # erase all independent", "anything if polygons mode is already active if self.mode == \"polygons\": return self.set_polygons_mode()", "in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if i >= 0 and i", "self.backup = [] ########################## # PAINT MODE VARIABLES # ########################## self.pen_size = 30", "returns the distance of two points (A, B) :param pt_a: Point A :param", "# TODO: add cleanup after circle drawing self.mode = \"paint\" # adjust widgets", "[] # type MyEllipse[] # holds colors of polygons \"Red\" or \"Blue\" self.polygon_colors", "the arena is -> everything not red is inside) # TODO: For some", "in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for j in range(point.y() - self.pen_size/2,", "def repaint_polygons(self): \"\"\" repaints all the polygons that are now changeable. :return: None", "0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result def is_in_scene(self, point): \"\"\" checks", "of polygons \"Red\" or \"Blue\" self.polygon_colors = [] # type string[] # holds", "point in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons)", "and j > 0 and j <= bg_height: try: self.paint_image.setPixel(i, j, value) except:", "self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button", "new points' position i = 0 for points in self.polygon_points: polygon = QtGui.QPolygonF()", "widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D))", "fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p =", "self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self)", "load BLUE channel (blue color shows where occultation is -> everything not blue", "fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE", "it's color and position are known :param polygon: QPolygonF to be painted :param", "= 30 # image to store all progress bg_height, bg_width = self.background.shape[:2] bg_size", "def save(self): \"\"\" Saves current image temporarily (to use with \"undo()\" later) :return:", "self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True)", "just fine. Arena mask is now working with alpha data, but # TODO:", "# use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and save", "the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True)", "if self.mode == \"polygons\": return self.set_polygons_mode() else: # don't do anything if polygons", "self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and left panel with buttons self.make_gui() def", "\"\"\" if self.finish_callback: # TODO: fix this so two different masks can be", "marks a point in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse", "# undo button can only be pushed in paint mode, but affects polygon", "close to any other already chosen point dist = self.get_distance(pt, pos) if dist", "self.mode == \"polygons\": # in the polygons mode, try to pick one point", "to 255 occultation_mask[occultation_mask == 0] = 255 # 4) set all blue pixels", "or \"paint\" or \"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\" # store last", "self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut", "get_distance(self, pt_a, pt_b): \"\"\" simple method that returns the distance of two points", "= [] # type MyEllipse[][] # temporary image to work with polygons self.poly_image", "mode is already active if self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self): #", "switch it to blue if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False)", "so they can't be used to create a mask. Mysteriously, # TODO: alpha", "ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries to create a", ":return: None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def", "0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0, 0,", "event): # get event position and calibrate to scene pos = self.get_event_pos(event) if", "label to show current pen settings :return: None \"\"\" if self.mode == \"paint\":", "paint mode is already active if self.mode == \"paint\": return self.set_paint_mode() elif value", "self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button =", "the polygons according to the new points' position i = 0 for points", "ellipse def paint_polygon(self): \"\"\" tries to create a new polygon from currently selected", "polygon self.polygon_points = [] # type MyEllipse[][] # temporary image to work with", "little red to 1 (temporary) arena_mask[arena_mask > 0] = 1 # 3) set", "cleanup after circle drawing # cleanup after paint mode is not needed self.poly_button.setVisible(True)", "return self.set_polygons_mode() else: # don't do anything if polygons mode is already active", "QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save()", "holds sets of all used points. Each list corresponds to one polygon self.polygon_points", "0 and j <= bg_height: try: self.paint_image.setPixel(i, j, value) except: pass # set", "Qpoint or QPointF :return: True or False \"\"\" height, width = self.background.shape[:2] if", "a place to hide (it is visible) \"\"\" img = self.merge_images() bg_height, bg_width", "polygon and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the points", "\"Eraser\" button, there are no erasers in polygons mode self.color_buttons[2].setVisible(False) # in case", "the final image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt", "lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint a point", "QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the outside of the arena with", "G, B, A]. # To extract mask data, only Red (0) and Blue", "[] self.polygon_points = [] self.polygon_colors = [] # cleanup after paint mode is", "i = 0 for points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = []", "and left panel with buttons self.make_gui() def switch_color(self): text = self.sender().text() if self.DEBUG:", "pixels that contain at least a little red to 1 (temporary) arena_mask[arena_mask >", "# self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2) # TODO: label", "self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if self.mode == \"paint\": point", "mode, but affects polygon painting too (all polygons are saved # as one", "\"\"\" merges the 3 images (paint, polygons and circles) into one result :return:", "main view and left panel with buttons self.make_gui() def switch_color(self): text = self.sender().text()", "QGraphicsItem (from MyEllipse) \"\"\" # picks and marks a point in the polygon", "[] self.polygon_colors = [] # cleanup after paint mode is not needed self.mode", "change pen size :param value: new pen size :return: None \"\"\" # change", "to scene pos = self.get_event_pos(event) if not pos: # if pos isn't in", "and key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear", "key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint", "channels are full of 0, so they can't be used to create a", "# Color values in image are formatted [R, G, B, A]. # To", "position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if self.mode ==", "self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) #", "if len(self.backup) > 10: self.backup.pop(0) def undo(self): if self.mode == \"paint\": lenght =", "bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) #", "clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self,", "arena with red and use blue to mark possible\" \" hiding places. Unresolvable", "\"paint\": return self.set_paint_mode() elif value == \"Polygon mode\": # don't do anything if", "and Blue (2) channels are needed. # Create arena mask: 0 - outside,", "color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color)", "panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False)", "self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return False def save(self): \"\"\" Saves current", "% self.pen_size) def remove_items(self): \"\"\" remove all points from polygons mode from the", "# - clear the memory self.point_items = [] self.polygon_points = [] self.polygon_colors =", "in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there are no erasers in polygons", "QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color)", "B :return: float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y()", "4) set all blue pixels (value 1) to 0 occultation_mask[occultation_mask == 1] =", "save last 10 images img = self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0)", "key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key", "QtGui.QPolygonF() for el in self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) #", "label.setText(\"Welcome to arena editor! Paint the outside of the arena with red and", "width and point.y() <= height: return True else: return False def make_gui(self): \"\"\"", "[R, G, B, A]. # To extract mask data, only Red (0) and", "can't be used to create a mask. Mysteriously, # TODO: alpha channel seems", "change_pen_size(self, value): \"\"\" change pen size :param value: new pen size :return: None", "# don't do anything if polygons mode is already active if self.mode ==", "Saves current image temporarily (to use with \"undo()\" later) :return: \"\"\" # save", "everything not blue is visible or outside of the arena) occultation_mask = np.array(img_arr[:,:,2],", "self.mode == \"circles\": return self.set_circles_mode() def set_paint_mode(self): # join the temporary images with", "paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True)", "elif self.color == \"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0, 0, 100) else:", "point is in the scene self.draw(point) # do nothing in \"polygons\" mode def", "polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen as a color, switch", "self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry,", "to hide (it is visible) \"\"\" img = self.merge_images() bg_height, bg_width = self.background.shape[:2]", ":return: the final image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height)", "self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30)", "self.pen_size/2, point.y() + self.pen_size/2): if i >= 0 and i < bg_width and", "so two different masks can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else:", "print(\"Polygon complete, drawing it\") # create the polygon polygon = QtGui.QPolygonF() for el", "# in the polygons mode, try to pick one point precision = 20", "point.y() <= height: return True else: return False def make_gui(self): \"\"\" Creates the", "Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self)", "do anything if polygons mode is already active if self.mode == \"circles\": return", "pt_b: Point B :return: float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2", "-> everything not blue is visible or outside of the arena) occultation_mask =", "img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self):", "self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current", "the temporary images with paint image self.save() self.refresh_image(self.merge_images()) # clean the temporary images", "sure no other button stays pushed for button in self.color_buttons: if button.text() !=", "MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img,", "QPoint) if type(point) == QtCore.QPointF: point = point.toPoint() # use current pen color", "Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500, -500) ex.showMaximized() ex.setFocus() app.exec_() app.deleteLater() sys.exit()", "img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap =", "active if self.mode == \"paint\": return self.set_paint_mode() elif value == \"Polygon mode\": #", "pos) if dist < precision: print(\"Too close2\") ok = False if ok: self.point_items.append(self.pick_point(pos))", "# Create occlusion mask: 0 - occultation, 255 - visible spot # 1)", "= [] self.polygon_points = [] self.polygon_colors = [] # cleanup after paint mode", "float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y() - pt_a.y())", "with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image))", "== \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100) elif self.color == \"Outside of\\nthe", "clear everything and start over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items =", "will be considered red.\") widget.layout().addWidget(label) # SWITCH button and key shortcut mode_switch_group =", "around the point position bg_height, bg_width = self.background.shape[:2] for i in range(point.x() -", "in paint mode :param point: point to be drawn :return: None \"\"\" #", "image to work with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0))", "self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint mode \"polygons\"", "# 1) load BLUE channel (blue color shows where occultation is -> everything", "value = self.sender().text() if value == \"Paint mode\": # don't do anything if", "displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in self.color_buttons: button.setVisible(True)", "\"\"\" # picks and marks a point in the polygon mode brush =", "bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap", "\"Polygon mode\": # don't do anything if polygons mode is already active if", "255 - inside # 1) load RED channel (red color shows where outside", "self.point_items: # check if the clicked pos isn't too close to any other", "the same time. (they both share the same alpha channel) arena_mask = np.array(img_arr[:,:,3],", "of\\nthe arena\": value = QtGui.qRgba(255, 0, 0, 100) else: value = QtGui.qRgba(0, 0,", "# remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def draw(self, point):", "self.polygon_colors = [] def mouse_press_event(self, event): # get event position and calibrate to", "= QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points =", "# change float to int (QPointF -> QPoint) if type(point) == QtCore.QPointF: point", "GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout())", "set all pixels with no color (arena inside) to 255 arena_mask[arena_mask == 0]", "it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the points (ellipses), too self.polygon_points.append(self.point_items)", "to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint", "self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def undo(self): if self.mode == \"paint\": lenght", "self.DEBUG: print(\"Polygon is too small, pick at least 3 points\") return False def", "mode\": # don't do anything if polygons mode is already active if self.mode", "working with alpha data, but # TODO: occultation mask cannot be used at", "are full of 0, so they can't be used to create a mask.", "QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter() p.begin(result)", "mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button =", "and circles) into one result :return: the final image \"\"\" bg_height, bg_width =", "blue to mark possible\" \" hiding places. Unresolvable colors will be considered red.\")", "range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if i >= 0 and i <", "self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there are no erasers in polygons mode", "mask: 0 - outside, 255 - inside # 1) load RED channel (red", "set all pixels with no color (arena inside) to 255 occultation_mask[occultation_mask == 0]", "the polygon and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the", "p = Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500, -500) ex.showMaximized() ex.setFocus() app.exec_()", "PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3,", "self.pen_size = 30 # image to store all progress bg_height, bg_width = self.background.shape[:2]", "[] self.polygon_colors = [] # TODO: add cleanup after circle drawing self.mode =", "pixels that contain at least a little blue to 1 (temporary) occultation_mask[occultation_mask >", "\"paint\": point = self.get_event_pos(event) if point: # if point is in the scene", "def clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def", "100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the", "mode\": # don't do anything if paint mode is already active if self.mode", "seems to be working just fine. Arena mask is now working with alpha", "super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img self.project = project self.view", "- outside, 255 - inside # 1) load RED channel (red color shows", "self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN", "(QPointF -> QPoint) if type(point) == QtCore.QPointF: point = point.toPoint() # use current", "(MyEllipses) :return: bool, whether the polygon was drawn \"\"\" # check if polygon", "to the new points' position i = 0 for points in self.polygon_points: polygon", "# refresh text in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the label to", "\"\"\" change pen size :param value: new pen size :return: None \"\"\" #", "CLEAR button and key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button", "same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels", "\"undo()\" later) :return: \"\"\" # save last 10 images img = self.paint_image.copy() self.backup.append(img)", "self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button)", "inside) to 255 occultation_mask[occultation_mask == 0] = 255 # 4) set all blue", "blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button)", "self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui", "self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there are", "drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn", "two different masks can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: #", "be considered red.\") widget.layout().addWidget(label) # SWITCH button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget)", "\"\"\" Saves current image temporarily (to use with \"undo()\" later) :return: \"\"\" #", "# don't do anything if paint mode is already active if self.mode ==", "the new points' position i = 0 for points in self.polygon_points: polygon =", "scene return if self.mode == \"polygons\": # in the polygons mode, try to", "if self.is_in_scene(point): return point else: return False def save(self): \"\"\" Saves current image", "# hide \"Eraser\" button, there are no erasers in polygons mode self.color_buttons[2].setVisible(False) #", "self.set_label_text() def set_label_text(self): \"\"\" changes the label to show current pen settings :return:", "pos isn't in the scene return if self.mode == \"polygons\": # in the", "bg_height, bg_width = self.background.shape[:2] for i in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2):", "clear the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points = [] # go", "supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30,", "= img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def", "remove all points from polygons mode from the scene :return: \"\"\" # erase", "self.mode == \"paint\": lenght = len(self.backup) if lenght > 0: img = self.backup.pop(lenght-1)", "arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget)", "<= bg_height: try: self.paint_image.setPixel(i, j, value) except: pass # set new image and", "used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2) # TODO:", "circle drawing # cleanup after paint mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False)", "self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything and start over :return: None \"\"\"", "def paint_polygon_(self, polygon, color): \"\"\" paints a polygon, when it's color and position", "type string[] # holds sets of all used points. Each list corresponds to", "self.pen_size = value # refresh text in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes", "self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if self.mode == \"paint\":", "SWITCH button and key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button)", "remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove", "painted :param color: \"Red\" or \"Blue\" :return: None \"\"\" # setup the painter", "# erase all points from polygons for point_items in self.polygon_points: for point in", "0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0,", "is -> everything not red is inside) # TODO: For some reason, color", "pixels with no color (arena inside) to 255 occultation_mask[occultation_mask == 0] = 255", "fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view", "bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size,", "\"\"\" repaints all the polygons that are now changeable. :return: None \"\"\" #", "= self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y() <= height: return", "import cv2 import sys import math import numpy as np from core.project.project import", "image to work with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0))", "0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES #", "== \"paint\": return self.set_paint_mode() elif value == \"Polygon mode\": # don't do anything", "QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0))", "QPointF :return: True or False \"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and", "create a mask. Mysteriously, # TODO: alpha channel seems to be working just", "(they are not yet part of any polygon) self.point_items = [] # type", "self.merge_images() bg_height, bg_width = self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width,", "in paint mode, but affects polygon painting too (all polygons are saved #", "to store all progress bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt", "# TODO: fix this so two different masks can be used # self.finish_callback(arena_mask,", "= QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget = QtGui.QWidget()", "False for points in self.polygon_points: for pt in points: dist = self.get_distance(pt, pos)", "# create the main view and left panel with buttons self.make_gui() def switch_color(self):", "self.color == \"Outside of\\nthe arena\": value = QtGui.qRgba(255, 0, 0, 100) else: value", "but affects polygon painting too (all polygons are saved # as one step)", "0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self):", "eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\")", "later return arena_mask, None def change_pen_size(self, value): \"\"\" change pen size :param value:", "<gh_stars>1-10 __author__ = 'dita' from PyQt4 import QtGui, QtCore import cv2 import sys", "for points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = [] for point in", "QtGui.qRgba(0, 0, 0, 0) # paint the area around the point position bg_height,", "paint mode \"polygons\" or \"paint\" or \"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\"", "__init__(self, img, project, finish_callback=None): # TODO: add support for the original arena editor", "mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles", "occultation mask cannot be used at the same time. (they both share the", "self.polygon_points = [] self.polygon_colors = [] # cleanup after paint mode is not", "scene :param point: Qpoint or QPointF :return: True or False \"\"\" height, width", "self.color_buttons: button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" #", "self.polygon_colors.append(self.color) # store all the points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary points'", "self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon)", "0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0,", "self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\") self.poly_button.clicked.connect(self.paint_polygon) widget.layout().addWidget(self.poly_button) # CLEAR", "30 # image to store all progress bg_height, bg_width = self.background.shape[:2] bg_size =", "color, switch it to blue if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True)", "painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the polygon if", "= [] ########################## # PAINT MODE VARIABLES # ########################## self.pen_size = 30 #", "# save last 10 images img = self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10:", "p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result", "= QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\")", "= QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow)", "points. Each list corresponds to one polygon self.polygon_points = [] # type MyEllipse[][]", "mark possible\" \" hiding places. Unresolvable colors will be considered red.\") widget.layout().addWidget(label) #", "= \"polygons\" # TODO: add cleanup after circle drawing # cleanup after paint", "10 images img = self.paint_image.copy() self.backup.append(img) if len(self.backup) > 10: self.backup.pop(0) def undo(self):", "not yet part of any polygon) self.point_items = [] # type MyEllipse[] #", "at least a little blue to 1 (temporary) occultation_mask[occultation_mask > 0] = 1", "event): if self.mode == \"paint\": point = self.get_event_pos(event) if point: # if point", "colors of polygons \"Red\" or \"Blue\" self.polygon_colors = [] # type string[] #", "popup(self): \"\"\" converts image to numpy arrays :return: tuple (arena_mask, occultation_mask) True in", "create the polygon polygon = QtGui.QPolygonF() for el in self.point_items: # use all", "= [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside", "set new image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple method", "== \"Paint mode\": # don't do anything if paint mode is already active", "\"polygons\" or \"paint\" or \"circles\" self.mode = \"\" self.color = \"Hiding\\nplaces\" # store", "QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint mode", "img, project, finish_callback=None): # TODO: add support for the original arena editor (circle)", "points and polygons self.remove_items() # - clear the memory self.point_items = [] self.polygon_points", "Creates the widget. It is a separate method purely to save space :return:", "needed. # Create arena mask: 0 - outside, 255 - inside # 1)", "to 0 occultation_mask[occultation_mask == 1] = 0 \"\"\" if self.finish_callback: # TODO: fix", "(paint, polygons and circles) into one result :return: the final image \"\"\" bg_height,", "# 1) load RED channel (red color shows where outside of the arena", "VARIABLES # ########################## self.pen_size = 30 # image to store all progress bg_height,", "that the user has chosen to be a future part of a polygon", "def get_distance(self, pt_a, pt_b): \"\"\" simple method that returns the distance of two", "visible spot # 1) load BLUE channel (blue color shows where occultation is", "self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo = QtGui.QAction('undo',", "4) set all red pixels (value 1) to 0 arena_mask[arena_mask == 1] =", "to be a future part of a polygon :param position: :return: QGraphicsItem (from", "too small, pick at least 3 points\") return False def paint_polygon_(self, polygon, color):", "point: # if point is in the scene self.draw(point) # do nothing in", "of any polygon) self.point_items = [] # type MyEllipse[] # holds colors of", "paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button) circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode)", "button.setVisible(True) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(True) self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" # TODO:", "color (arena inside) to 255 occultation_mask[occultation_mask == 0] = 255 # 4) set", "0, 0, 100) else: qc = QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc)", "Blue (2) channels are needed. # Create arena mask: 0 - outside, 255", "mode, try to pick one point precision = 20 ok = True for", "refresh text in QLabel self.set_label_text() def set_label_text(self): \"\"\" changes the label to show", "refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap", "= img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in image", "self.mode == \"paint\": point = self.get_event_pos(event) if point: # if point is in", "if polygons mode is already active if self.mode == \"polygons\": return self.set_polygons_mode() else:", "= cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im, p) ex.show()", "part of any polygon) self.point_items = [] # type MyEllipse[] # holds colors", "points' position i = 0 for points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse", "changes the label to show current pen settings :return: None \"\"\" if self.mode", "def switch_mode(self): value = self.sender().text() if value == \"Paint mode\": # don't do", "fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt) self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap =", "are needed. # Create arena mask: 0 - outside, 255 - inside #", "self.polygon_colors = [] # type string[] # holds sets of all used points.", "img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in image are formatted [R,", "occultation_mask[occultation_mask == 1] = 0 \"\"\" if self.finish_callback: # TODO: fix this so", "in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = [] for point in points: qpt", "# Create arena mask: 0 - outside, 255 - inside # 1) load", "masks can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None) else: # print label(arena_mask,", "- self.pen_size/2, point.y() + self.pen_size/2): if i >= 0 and i < bg_width", "0 for points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = [] for point", "= 1 # 3) set all pixels with no color (arena inside) to", "final image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt =", "= 'dita' from PyQt4 import QtGui, QtCore import cv2 import sys import math", "panel with buttons self.make_gui() def switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting color", "full of 0, so they can't be used to create a mask. Mysteriously,", "if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y() <= height: return True else:", "\"polygons\": # in the polygons mode, try to pick one point precision =", "self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there", "if color == \"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0, 0, 100) else:", "of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels that", "temporary points' storage self.point_items = [] return True else: if self.DEBUG: print(\"Polygon is", "be painted :param color: \"Red\" or \"Blue\" :return: None \"\"\" # setup the", "False \"\"\" height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and", "selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and save it's color self.paint_polygon_(polygon,", "widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width to", "pos) if dist < precision: print(\"Too close\") ok = False for points in", "30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut", "gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG =", "repaint_polygons(self): \"\"\" repaints all the polygons that are now changeable. :return: None \"\"\"", "the polygons mode, try to pick one point precision = 20 ok =", "it\") # create the polygon polygon = QtGui.QPolygonF() for el in self.point_items: #", "blue pixels (value 1) to 0 occultation_mask[occultation_mask == 1] = 0 \"\"\" if", "if point is in the scene self.draw(point) # do nothing in \"polygons\" mode", ":param value: new pen size :return: None \"\"\" # change pen size self.pen_size", "self.backup.pop(0) def undo(self): if self.mode == \"paint\": lenght = len(self.backup) if lenght >", "# draw the polygon and save it's color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store", "pixels (value 1) to 0 occultation_mask[occultation_mask == 1] = 0 \"\"\" if self.finish_callback:", "\"paint\" # adjust widgets displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for", "points for point in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything and start", "40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO", "mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons =", "= QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key shortcut self.action_paint_polygon =", "arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels that contain at", "circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) #", "# in case \"Eraser\" was chosen as a color, switch it to blue", "# go through all saved points and recreate the polygons according to the", "img self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) #", "if button.text() != text: button.setChecked(False) else: button.setChecked(True) self.color = text def switch_mode(self): value", "+ self.pen_size/2): for j in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if i", "from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True", "[] ########################## # PAINT MODE VARIABLES # ########################## self.pen_size = 30 # image", "self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and", "is inside the scene :param point: Qpoint or QPointF :return: True or False", "0 # invert mask arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion mask: 0", "MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse) return ellipse def paint_polygon(self): \"\"\" tries to create", ":return: tuple (arena_mask, occultation_mask) True in arena_masks means that the point is INSIDE", "dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels that contain at least a little", "self.get_event_pos(event) if not pos: # if pos isn't in the scene return if", "return self.set_paint_mode() elif value == \"Polygon mode\": # don't do anything if polygons", "for j in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if i >= 0", "math.sqrt((pt_b.x() - pt_a.x()) ** 2 + (pt_b.y() - pt_a.y()) ** 2) def pick_point(self,", "self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo)", "self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y() <= height: return True", "that the point is NOT a place to hide (it is visible) \"\"\"", "QtGui.qRgba(0, 0, 255, 100) elif self.color == \"Outside of\\nthe arena\": value = QtGui.qRgba(255,", "mode is already active if self.mode == \"paint\": return self.set_paint_mode() elif value ==", "pos: # if pos isn't in the scene return if self.mode == \"polygons\":", "shows where occultation is -> everything not blue is visible or outside of", "0, 0, 0)) self.refresh_circles_image() def draw(self, point): \"\"\" paint a point with a", "CIRCLES MODE VARIABLES # ########################## # TODO: add circles mode variables # temporary", "0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and left", "mode is not needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) #", "the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv) # im", "if self.DEBUG: print(\"Polygon complete, drawing it\") # create the polygon polygon = QtGui.QPolygonF()", "method purely to save space :return: None \"\"\" ########################## # GUI # ##########################", "# store the current paint mode \"polygons\" or \"paint\" or \"circles\" self.mode =", "0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all drawn lines self.poly_image.fill(QtGui.qRgba(0, 0,", "self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary images with", "current pen color if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100)", "[] for point in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i])", "widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width to 300px", "check if polygon can be created if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon", "do anything if paint mode is already active if self.mode == \"paint\": return", "blue if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False)", "self.refresh_image(img) def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self):", "self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0,", "= QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if", "scene self.draw(point) # do nothing in \"polygons\" mode def get_event_pos(self, event): point =", "i >= 0 and i < bg_width and j > 0 and j", "(temporary) arena_mask[arena_mask > 0] = 1 # 3) set all pixels with no", "of the arena with red and use blue to mark possible\" \" hiding", "TODO: add support for the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback", "math import numpy as np from core.project.project import Project from gui.img_controls import gui_utils", "\"polygons\" # TODO: add cleanup after circle drawing # cleanup after paint mode", "import numpy as np from core.project.project import Project from gui.img_controls import gui_utils from", "if self.color == \"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100) elif self.color ==", "self.set_circles_mode() def set_paint_mode(self): # join the temporary images with paint image self.save() self.refresh_image(self.merge_images())", "self.is_in_scene(point): return point else: return False def save(self): \"\"\" Saves current image temporarily", "def paint_polygon(self): \"\"\" tries to create a new polygon from currently selected points", "is not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons:", "well, uncomment later return arena_mask, None def change_pen_size(self, value): \"\"\" change pen size", "result = QtGui.QImage(bg_size, fmt) result.fill(QtGui.qRgba(0, 0, 0, 0)) p = QtGui.QPainter() p.begin(result) p.drawImage(0,", "where outside of the arena is -> everything not red is inside) #", "the canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points = [] # go through", "\"Outside of\\nthe arena\": qc = QtGui.QColor(255, 0, 0, 100) else: qc = QtGui.QColor(0,", "1) to 0 arena_mask[arena_mask == 1] = 0 # invert mask arena_mask =", "arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion mask: 0 - occultation, 255 -", "red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label =", "# TODO: add cleanup after circle drawing # cleanup after paint mode is", "= self.get_distance(pt, pos) if dist < precision: print(\"Too close\") ok = False for", "B, A]. # To extract mask data, only Red (0) and Blue (2)", "self.layout().addWidget(self.view) if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im", "BLUE channel (blue color shows where occultation is -> everything not blue is", "after circle drawing self.mode = \"paint\" # adjust widgets displayed in the left", "2) def pick_point(self, position): \"\"\" create a point that the user has chosen", "support the \"undo\" function # undo button can only be pushed in paint", "they can't be used to create a mask. Mysteriously, # TODO: alpha channel", "adjust widgets displayed in the left panel self.poly_button.setVisible(False) self.undo_button.setVisible(True) self.slider.setVisible(True) for button in", "pen settings :return: None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" %", "clear temporary points' storage self.point_items = [] return True else: if self.DEBUG: print(\"Polygon", "one result :return: the final image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size =", "self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses for point in self.point_items:", "== 1] = 0 # invert mask arena_mask = np.invert(arena_mask) \"\"\" # Create", "widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not", "1 # 3) set all pixels with no color (arena inside) to 255", "space :return: None \"\"\" ########################## # GUI # ########################## self.setLayout(QtGui.QHBoxLayout()) self.layout().setAlignment(QtCore.Qt.AlignBottom) # left", "type MyEllipse[][] # temporary image to work with polygons self.poly_image = QtGui.QImage(bg_size, fmt)", "widget.setMinimumWidth(300) label = QtGui.QLabel() label.setWordWrap(True) label.setText(\"Welcome to arena editor! Paint the outside of", "QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main", "points from polygons for point_items in self.polygon_points: for point in point_items: self.scene.removeItem(point) #", "C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the", "text)) # make sure no other button stays pushed for button in self.color_buttons:", "self.polygon_colors = [] # TODO: add cleanup after circle drawing self.mode = \"paint\"", "255 # 4) set all blue pixels (value 1) to 0 occultation_mask[occultation_mask ==", "the event position self.save() self.draw(pos) def mouseReleaseEvent(self, event): self.save() def mouse_moving(self, event): if", "of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button)", "= QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES", "= np.invert(arena_mask) \"\"\" # Create occlusion mask: 0 - occultation, 255 - visible", "and recreate the polygons according to the new points' position i = 0", "to numpy arrays :return: tuple (arena_mask, occultation_mask) True in arena_masks means that the", "(0) and Blue (2) channels are needed. # Create arena mask: 0 -", "are known :param polygon: QPolygonF to be painted :param color: \"Red\" or \"Blue\"", "isn't too close to any other already chosen point dist = self.get_distance(pt, pos)", "self.background.shape[:2] ptr = img.constBits() ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color values", "\"Eraser\" was chosen as a color, switch it to blue if self.color ==", "text def switch_mode(self): value = self.sender().text() if value == \"Paint mode\": # don't", "2: if self.DEBUG: print(\"Polygon complete, drawing it\") # create the polygon polygon =", "0 \"\"\" if self.finish_callback: # TODO: fix this so two different masks can", "# set left panel widget width to 300px widget.setMaximumWidth(300) widget.setMinimumWidth(300) label = QtGui.QLabel()", "= self.sender().text() if value == \"Paint mode\": # don't do anything if paint", "self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to numpy arrays :return: tuple", "\"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self): \"\"\"", "eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel() self.pen_label.setWordWrap(True) self.pen_label.setText(\"\") widget.layout().addWidget(self.pen_label) self.circle_label =", "set_label_text(self): \"\"\" changes the label to show current pen settings :return: None \"\"\"", "support for the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback", "self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider)", "cleanup after paint mode is not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False)", "for button in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button, there are no erasers", "= QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the", "\"\"\" # check if polygon can be created if len(self.point_items) > 2: if", "key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\")", "polygon = QtGui.QPolygonF() for el in self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(),", "occultation_mask[occultation_mask > 0] = 1 # 3) set all pixels with no color", "button can only be pushed in paint mode, but affects polygon painting too", "return False def make_gui(self): \"\"\" Creates the widget. It is a separate method", "= QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end()", "point: Qpoint or QPointF :return: True or False \"\"\" height, width = self.background.shape[:2]", "self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple method that returns the distance of", "list corresponds to one polygon self.polygon_points = [] # type MyEllipse[][] # temporary", "0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return result def is_in_scene(self,", "\"\"\" checks if the point is inside the scene :param point: Qpoint or", ":param pt_b: Point B :return: float distance \"\"\" return math.sqrt((pt_b.x() - pt_a.x()) **", ">= 0 and i < bg_width and j > 0 and j <=", "MyEllipse[] # holds colors of polygons \"Red\" or \"Blue\" self.polygon_colors = [] #", "self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES #", "of\\nthe arena\": qc = QtGui.QColor(255, 0, 0, 100) else: qc = QtGui.QColor(0, 0,", "whether the polygon was drawn \"\"\" # check if polygon can be created", "self.slider.setGeometry(30, 40, 50, 30) self.slider.setRange(3, 50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) #", "set_polygons_mode(self): self.mode = \"polygons\" # TODO: add cleanup after circle drawing # cleanup", "brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image() def repaint_polygons(self):", "occultation_mask means that the point is NOT a place to hide (it is", "polygon from currently selected points (MyEllipses) :return: bool, whether the polygon was drawn", "= [] # TODO: add cleanup after circle drawing self.mode = \"paint\" #", "paint_polygon(self): \"\"\" tries to create a new polygon from currently selected points (MyEllipses)", "j <= bg_height: try: self.paint_image.setPixel(i, j, value) except: pass # set new image", "merges the 3 images (paint, polygons and circles) into one result :return: the", "same time. (they both share the same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\")", "polygon painting too (all polygons are saved # as one step) self.backup =", "is visible or outside of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2)", "# temporary image to work with polygons self.poly_image = QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0,", "QtGui.QApplication(sys.argv) # im = cv2.imread('/home/dita/PycharmProjects/sample2.png') im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex =", "255 occultation_mask[occultation_mask == 0] = 255 # 4) set all blue pixels (value", "or \"Blue\" self.polygon_colors = [] # type string[] # holds sets of all", "\"undo\" function # undo button can only be pushed in paint mode, but", "self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the temporary images with paint", "pt_a, pt_b): \"\"\" simple method that returns the distance of two points (A,", "for i in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for j in range(point.y()", "if lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image =", "self.paint_image.setPixel(i, j, value) except: pass # set new image and pixmap self.refresh_image(self.paint_image) def", "that returns the distance of two points (A, B) :param pt_a: Point A", "picks and marks a point in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0, 0,", "self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to numpy arrays :return:", "self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to numpy arrays :return: tuple (arena_mask,", "pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image", "pt_a.y()) ** 2) def pick_point(self, position): \"\"\" create a point that the user", "self.circle_label.setVisible(False) self.set_label_text() def set_polygons_mode(self): self.mode = \"polygons\" # TODO: add cleanup after circle", "at least a little red to 1 (temporary) arena_mask[arena_mask > 0] = 1", "> 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap)", "self.remove_items() # - clear the memory self.point_items = [] self.polygon_points = [] self.polygon_colors", "to 255 arena_mask[arena_mask == 0] = 255 # 4) set all red pixels", ":param pt_a: Point A :param pt_b: Point B :return: float distance \"\"\" return", "range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for j in range(point.y() - self.pen_size/2, point.y()", "# check if the clicked pos isn't too close to any other already", "else: value = QtGui.qRgba(0, 0, 0, 0) # paint the area around the", "needed self.poly_button.setVisible(True) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(True) # hide \"Eraser\" button,", "blue to 1 (temporary) occultation_mask[occultation_mask > 0] = 1 # 3) set all", "self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap", "self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo = QtGui.QAction('undo', self)", "mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return", "create a point that the user has chosen to be a future part", "MODE VARIABLES # ########################## # TODO: add circles mode variables # temporary image", "size self.pen_size = value # refresh text in QLabel self.set_label_text() def set_label_text(self): \"\"\"", "occultation_mask[occultation_mask == 0] = 255 # 4) set all blue pixels (value 1)", "img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self, img): self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap =", "# invert mask arena_mask = np.invert(arena_mask) \"\"\" # Create occlusion mask: 0 -", "editor! Paint the outside of the arena with red and use blue to", "None \"\"\" # change float to int (QPointF -> QPoint) if type(point) ==", "\"\"\" create a point that the user has chosen to be a future", "\"\"\" simple method that returns the distance of two points (A, B) :param", "pick one point precision = 20 ok = True for pt in self.point_items:", "255 # 4) set all red pixels (value 1) to 0 arena_mask[arena_mask ==", "drawing it\") # create the polygon polygon = QtGui.QPolygonF() for el in self.point_items:", "len(self.backup) > 10: self.backup.pop(0) def undo(self): if self.mode == \"paint\": lenght = len(self.backup)", "def mouse_moving(self, event): if self.mode == \"paint\": point = self.get_event_pos(event) if point: #", "the point is NOT a place to hide (it is visible) \"\"\" img", "color self.paint_polygon_(polygon, self.color) self.polygon_colors.append(self.color) # store all the points (ellipses), too self.polygon_points.append(self.point_items) #", "self.circle_label = QtGui.QLabel() self.circle_label.setWordWrap(True) self.circle_label.setText(\"Sorry, not supported yet\") widget.layout().addWidget(self.circle_label) # PEN SIZE slider", "after polygon drawing # - remove all points and polygons self.remove_items() # -", "0, 0)) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) # create the main view and left panel", "# refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the polygons that", "not red is inside) # TODO: For some reason, color channels are full", "= QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width to 300px widget.setMaximumWidth(300)", "erase all points from polygons for point_items in self.polygon_points: for point in point_items:", "# picks and marks a point in the polygon mode brush = QtGui.QBrush(QtGui.QColor(0,", "MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store", "Project from gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView", "widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\":", "QtGui.QPolygonF() tmp_ellipse = [] for point in points: qpt = QtCore.QPointF(point.x(), point.y()) polygon.append(qpt)", "= 0 for points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = [] for", "= QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(paintmode_button)", "self.finish_callback: # TODO: fix this so two different masks can be used #", "if i >= 0 and i < bg_width and j > 0 and", "too self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items = [] return True else:", "self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint mode \"polygons\" or \"paint\" or \"circles\"", "import gui_utils from gui.arena.my_ellipse import MyEllipse from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG", "the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the polygons that are now", "height: return True else: return False def make_gui(self): \"\"\" Creates the widget. It", "########################## # TODO: add circles mode variables # temporary image to work with", "# set new image and pixmap self.refresh_image(self.paint_image) def get_distance(self, pt_a, pt_b): \"\"\" simple", "return False def save(self): \"\"\" Saves current image temporarily (to use with \"undo()\"", "self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES", "uncomment later return arena_mask, None def change_pen_size(self, value): \"\"\" change pen size :param", "to 1 (temporary) arena_mask[arena_mask > 0] = 1 # 3) set all pixels", "# TODO: alpha channel seems to be working just fine. Arena mask is", "# UNDO key shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button =", "it to blue if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True)", "values in image are formatted [R, G, B, A]. # To extract mask", "image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint mode \"polygons\" or \"paint\" or", "point that the user has chosen to be a future part of a", "50) self.slider.setTickInterval(3) self.slider.setValue(30) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.valueChanged[int].connect(self.change_pen_size) self.slider.setVisible(False) widget.layout().addWidget(self.slider) # UNDO key shortcut self.action_undo =", "erasers in polygons mode self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen as a", "lines self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove all drawn lines", "key shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button", "a color, switch it to blue if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\"", "self.finish_callback(arena_mask, None) else: # print label(arena_mask, connectivity=2) # TODO: label seems to be", "def undo(self): if self.mode == \"paint\": lenght = len(self.backup) if lenght > 0:", "= \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def set_circles_mode(self): # join the", "new polygon from currently selected points (MyEllipses) :return: bool, whether the polygon was", "already chosen point dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close\")", "\"Blue\" :return: None \"\"\" # setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush", "0] = 255 # 4) set all blue pixels (value 1) to 0", "self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view)", "text: button.setChecked(False) else: button.setChecked(True) self.color = text def switch_mode(self): value = self.sender().text() if", "draw(self, point): \"\"\" paint a point with a pen in paint mode :param", "= np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all pixels that contain at least", "= self.scene.addPixmap(QtGui.QPixmap.fromImage(self.paint_image)) self.save() ########################## # POLYGON MODE VARIABLES # ########################## # all independent", "check if the clicked pos isn't too close to any other already chosen", "Point A :param pt_b: Point B :return: float distance \"\"\" return math.sqrt((pt_b.x() -", "color: \"Red\" or \"Blue\" :return: None \"\"\" # setup the painter painter =", "QtGui.QImage(bg_size, fmt) self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE", "red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True)", "sys import math import numpy as np from core.project.project import Project from gui.img_controls", "current pen settings :return: None \"\"\" if self.mode == \"paint\": self.pen_label.setText(\"Pen size: %s\"", "to arena editor! Paint the outside of the arena with red and use", "shortcut self.action_undo = QtGui.QAction('undo', self) self.action_undo.triggered.connect(self.undo) self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo)", "np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback = finish_callback self.setMouseTracking(True) self.background = img self.project = project", "self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C)) self.addAction(self.action_clear) self.clear_button = QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button", "is INSIDE the arena True in occultation_mask means that the point is NOT", "TODO: For some reason, color channels are full of 0, so they can't", "widget.layout().addWidget(self.poly_button) # CLEAR button and key shortcut self.action_clear = QtGui.QAction('clear', self) self.action_clear.triggered.connect(self.reset) self.action_clear.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_C))", "position are known :param polygon: QPolygonF to be painted :param color: \"Red\" or", "do nothing in \"polygons\" mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point):", "im = cv2.imread('/Users/flipajs/Desktop/red_vid.png') p = Project() ex = ArenaEditor(im, p) ex.show() ex.move(-500, -500)", "print(\"Too close\") ok = False for points in self.polygon_points: for pt in points:", "points in self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = [] for point in points:", "change pen size self.pen_size = value # refresh text in QLabel self.set_label_text() def", "self.pen_size/2): for j in range(point.y() - self.pen_size/2, point.y() + self.pen_size/2): if i >=", "arena_mask[arena_mask == 1] = 0 # invert mask arena_mask = np.invert(arena_mask) \"\"\" #", "shortcut self.action_paint_polygon = QtGui.QAction('paint_polygon', self) self.action_paint_polygon.triggered.connect(self.paint_polygon) self.action_paint_polygon.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D)) self.addAction(self.action_paint_polygon) self.poly_button = QtGui.QPushButton(\"Draw polygons\\n(key D)\")", "in self.point_items: self.scene.removeItem(point) def reset(self): \"\"\" clear everything and start over :return: None", "# 2) set all pixels that contain at least a little red to", "QtCore.QPointF(point.x(), point.y()) polygon.append(qpt) tmp_ellipse.append(self.pick_point(qpt)) self.paint_polygon_(polygon, self.polygon_colors[i]) i += 1 tmp_ellipses.append(tmp_ellipse) self.polygon_points = tmp_ellipses", "image \"\"\" bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32", "points' storage self.point_items = [] return True else: if self.DEBUG: print(\"Polygon is too", "temporary images with paint image self.save() self.refresh_image(self.merge_images()) # clean the temporary images self.clear_poly_image()", "cannot be used at the same time. (they both share the same alpha", "channel (blue color shows where occultation is -> everything not blue is visible", "self.color_buttons[2].setVisible(False) # in case \"Eraser\" was chosen as a color, switch it to", "[] return True else: if self.DEBUG: print(\"Polygon is too small, pick at least", "to blue if self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True)", "all pixels that contain at least a little red to 1 (temporary) arena_mask[arena_mask", "# do nothing in \"polygons\" mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if", "point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return False def save(self): \"\"\"", "view and left panel with buttons self.make_gui() def switch_color(self): text = self.sender().text() if", "ptr.setsize(img.byteCount()) img_arr = np.array(ptr).reshape(bg_height, bg_width, 4) # Color values in image are formatted", "j, value) except: pass # set new image and pixmap self.refresh_image(self.paint_image) def get_distance(self,", "# image to store all progress bg_height, bg_width = self.background.shape[:2] bg_size = QtCore.QSize(bg_width,", "if self.DEBUG: print((\"Setting color to %s\" % text)) # make sure no other", "= self.background.shape[:2] bg_size = QtCore.QSize(bg_width, bg_height) fmt = QtGui.QImage.Format_ARGB32 self.paint_image = QtGui.QImage(bg_size, fmt)", "# PEN SIZE slider self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setFocusPolicy(QtCore.Qt.NoFocus) self.slider.setGeometry(30, 40, 50, 30)", "self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items = tmp_points def merge_images(self): \"\"\" merges", "to %s\" % text)) # make sure no other button stays pushed for", "paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle() #", "this so two different masks can be used # self.finish_callback(arena_mask, occultation_mask) self.finish_callback(arena_mask, None)", "color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button", "# left panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel", "the same alpha channel) arena_mask = np.array(img_arr[:,:,3], dtype=\"uint8\") np.set_printoptions(threshold=np.nan) # 2) set all", "get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return False def", "# 3) set all pixels with no color (arena inside) to 255 arena_mask[arena_mask", "tmp_points = [] # go through all saved points and recreate the polygons", "was drawn \"\"\" # check if polygon can be created if len(self.point_items) >", "= QtGui.QColor(0, 0, 255, 100) pen = QtGui.QPen(qc) brush.setColor(qc) brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon)", "get event position and calibrate to scene pos = self.get_event_pos(event) if not pos:", "all drawn lines self.paint_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_image(self.paint_image) def clear_poly_image(self): # remove all", "return True else: if self.DEBUG: print(\"Polygon is too small, pick at least 3", "panel widget widget = QtGui.QWidget() widget.setLayout(QtGui.QVBoxLayout()) widget.layout().setAlignment(QtCore.Qt.AlignTop) # set left panel widget width", "calibrate to scene pos = self.get_event_pos(event) if not pos: # if pos isn't", "channel (red color shows where outside of the arena is -> everything not", "self.pen_size) def remove_items(self): \"\"\" remove all points from polygons mode from the scene", "set all pixels that contain at least a little blue to 1 (temporary)", "point): \"\"\" paint a point with a pen in paint mode :param point:", "a little red to 1 (temporary) arena_mask[arena_mask > 0] = 1 # 3)", "outside of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels", "# type string[] # holds sets of all used points. Each list corresponds", "add cleanup after circle drawing self.mode = \"paint\" # adjust widgets displayed in", "widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button = QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True)", "color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label = QtGui.QLabel()", "np.set_printoptions(threshold=np.nan) # 2) set all pixels that contain at least a little red", "3) set all pixels with no color (arena inside) to 255 arena_mask[arena_mask ==", "== 0] = 255 # 4) set all red pixels (value 1) to", "from gui.arena.my_view import MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img, project,", "circle drawing self.mode = \"paint\" # adjust widgets displayed in the left panel", "\"paint\": self.pen_label.setText(\"Pen size: %s\" % self.pen_size) def remove_items(self): \"\"\" remove all points from", "= finish_callback self.setMouseTracking(True) self.background = img self.project = project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event)", "mode brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) ellipse = MyEllipse(update_callback=self.repaint_polygons) ellipse.setBrush(brush) ellipse.setPos(QtCore.QPoint(position.x(), position.y())) self.scene.addItem(ellipse)", "outside of the arena is -> everything not red is inside) # TODO:", "paint mode, but affects polygon painting too (all polygons are saved # as", "\"Hiding\\nplaces\" # store last 10 QImages to support the \"undo\" function # undo", "channels are needed. # Create arena mask: 0 - outside, 255 - inside", "100) else: value = QtGui.qRgba(0, 0, 0, 0) # paint the area around", "2 + (pt_b.y() - pt_a.y()) ** 2) def pick_point(self, position): \"\"\" create a", "precision = 20 ok = True for pt in self.point_items: # check if", "refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn lines self.paint_image.fill(QtGui.qRgba(0,", "self.poly_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_poly_image() def clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0,", "other button stays pushed for button in self.color_buttons: if button.text() != text: button.setChecked(False)", "shortcut mode_switch_group = QtGui.QButtonGroup(widget) polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button =", "small, pick at least 3 points\") return False def paint_polygon_(self, polygon, color): \"\"\"", "gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app = QtGui.QApplication(sys.argv) # im =", "polymode_button = QtGui.QRadioButton(\"Polygon mode\") mode_switch_group.addButton(polymode_button) polymode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(polymode_button) paintmode_button = QtGui.QRadioButton(\"Paint mode\") mode_switch_group.addButton(paintmode_button) paintmode_button.toggled.connect(self.switch_mode)", "pt_a.x()) ** 2 + (pt_b.y() - pt_a.y()) ** 2) def pick_point(self, position): \"\"\"", "= self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap =", "project self.view = MyView(update_callback_move=self.mouse_moving, update_callback_press=self.mouse_press_event) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) # background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background))", "button.setVisible(True) # hide \"Eraser\" button, there are no erasers in polygons mode self.color_buttons[2].setVisible(False)", "the memory self.point_items = [] self.polygon_points = [] self.polygon_colors = [] # cleanup", "currently selected points (MyEllipses) :return: bool, whether the polygon was drawn \"\"\" #", "pos = self.get_event_pos(event) if not pos: # if pos isn't in the scene", "height, width = self.background.shape[:2] if self.scene.itemsBoundingRect().contains(point) and point.x() <= width and point.y() <=", "pen size self.pen_size = value # refresh text in QLabel self.set_label_text() def set_label_text(self):", "Color values in image are formatted [R, G, B, A]. # To extract", "set all red pixels (value 1) to 0 arena_mask[arena_mask == 1] = 0", "< bg_width and j > 0 and j <= bg_height: try: self.paint_image.setPixel(i, j,", "painter.end() # refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\" repaints all the polygons", "point is NOT a place to hide (it is visible) \"\"\" img =", "self.polygon_points: polygon = QtGui.QPolygonF() tmp_ellipse = [] for point in points: qpt =", "isn't in the scene return if self.mode == \"polygons\": # in the polygons", "= QtGui.QPushButton(\"Hiding\\nplaces\") blue_button.setCheckable(True) blue_button.setChecked(True) blue_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(blue_button) self.color_buttons.append(blue_button) red_button = QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True)", "self.point_items = tmp_points def merge_images(self): \"\"\" merges the 3 images (paint, polygons and", "in \"polygons\" mode def get_event_pos(self, event): point = self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point", "self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove", "Create occlusion mask: 0 - occultation, 255 - visible spot # 1) load", "outside of the arena with red and use blue to mark possible\" \"", "polygon, when it's color and position are known :param polygon: QPolygonF to be", "canvas self.remove_items() self.clear_poly_image() tmp_ellipses = [] tmp_points = [] # go through all", "a point with a pen in paint mode :param point: point to be", "MyView class ArenaEditor(QtGui.QDialog): DEBUG = True def __init__(self, img, project, finish_callback=None): # TODO:", "# color switcher widget color_widget = QtGui.QWidget() color_widget.setLayout(QtGui.QHBoxLayout()) self.color_buttons = [] blue_button =", "QtGui.QPainter() p.begin(result) p.drawImage(0, 0, self.poly_image) p.drawImage(0, 0, self.paint_image) p.drawImage(0, 0, self.circles_image) p.end() return", "dtype=\"uint8\") # 2) set all pixels that contain at least a little blue", "= tmp_ellipses for point in self.point_items: pos = QtCore.QPoint(point.x(), point.y()) tmp_points.append(self.pick_point(pos)) self.point_items =", "self.save() ########################## # POLYGON MODE VARIABLES # ########################## # all independent points (they", "** 2 + (pt_b.y() - pt_a.y()) ** 2) def pick_point(self, position): \"\"\" create", "QtGui.QPushButton(\"Clear paint area\\n(key C)\") self.clear_button.clicked.connect(self.reset) widget.layout().addWidget(self.clear_button) self.popup_button = QtGui.QPushButton(\"Done!\") self.popup_button.clicked.connect(self.popup) widget.layout().addWidget(self.popup_button) self.set_label_text() paintmode_button.toggle()", "def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def", "project, finish_callback=None): # TODO: add support for the original arena editor (circle) np.set_printoptions(threshold=np.nan)", "clean after polygon drawing # - remove all points and polygons self.remove_items() #", "pixels with no color (arena inside) to 255 arena_mask[arena_mask == 0] = 255", "two points (A, B) :param pt_a: Point A :param pt_b: Point B :return:", "- pt_a.y()) ** 2) def pick_point(self, position): \"\"\" create a point that the", "int (QPointF -> QPoint) if type(point) == QtCore.QPointF: point = point.toPoint() # use", "red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button) self.color_buttons.append(eraser_button) widget.layout().addWidget(color_widget) self.pen_label", "used points. Each list corresponds to one polygon self.polygon_points = [] # type", "color): \"\"\" paints a polygon, when it's color and position are known :param", "circlemode_button = QtGui.QRadioButton(\"Circles mode\") mode_switch_group.addButton(circlemode_button) circlemode_button.toggled.connect(self.switch_mode) widget.layout().addWidget(circlemode_button) # color switcher widget color_widget =", "== \"polygons\": # in the polygons mode, try to pick one point precision", "lenght = len(self.backup) if lenght > 0: img = self.backup.pop(lenght-1) self.refresh_image(img) def refresh_image(self,", "the points (ellipses), too self.polygon_points.append(self.point_items) # clear temporary points' storage self.point_items = []", "with buttons self.make_gui() def switch_color(self): text = self.sender().text() if self.DEBUG: print((\"Setting color to", "can be created if len(self.point_items) > 2: if self.DEBUG: print(\"Polygon complete, drawing it\")", "setup the painter painter = QtGui.QPainter() painter.begin(self.poly_image) brush = QtGui.QBrush() # paint the", "self.point_items = [] return True else: if self.DEBUG: print(\"Polygon is too small, pick", "the \"undo\" function # undo button can only be pushed in paint mode,", "self.action_undo.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Z)) self.addAction(self.action_undo) self.undo_button = QtGui.QPushButton(\"Undo\\n(key Z)\") self.undo_button.clicked.connect(self.undo) widget.layout().addWidget(self.undo_button) # DRAW button and key", "value): \"\"\" change pen size :param value: new pen size :return: None \"\"\"", "self.point_items: # use all selected points polygon.append(QtCore.QPointF(el.x(), el.y())) # draw the polygon and", "p.drawImage(0, 0, self.circles_image) p.end() return result def is_in_scene(self, point): \"\"\" checks if the", "# background image self.scene.addPixmap(gui_utils.cvimg2qtpixmap(self.background)) self.view.setMouseTracking(True) # store the current paint mode \"polygons\" or", "close\") ok = False for points in self.polygon_points: for pt in points: dist", "button.setVisible(False) self.clear_button.setVisible(False) self.popup_button.setVisible(False) self.pen_label.setVisible(False) self.circle_label.setVisible(True) def popup(self): \"\"\" converts image to numpy arrays", "\"Hiding\\nplaces\": value = QtGui.qRgba(0, 0, 255, 100) elif self.color == \"Outside of\\nthe arena\":", "= self.view.mapToScene(event.pos()).toPoint() if self.is_in_scene(point): return point else: return False def save(self): \"\"\" Saves", "visible or outside of the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set", "value == \"Polygon mode\": # don't do anything if polygons mode is already", "self.set_paint_mode() elif value == \"Polygon mode\": # don't do anything if polygons mode", "def clear_circles_image(self): # remove all drawn lines self.circles_image.fill(QtGui.qRgba(0, 0, 0, 0)) self.refresh_circles_image() def", "else: if self.DEBUG: print(\"Polygon is too small, pick at least 3 points\") return", "refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self):", "pt_b): \"\"\" simple method that returns the distance of two points (A, B)", "self.polygon_points = [] # type MyEllipse[][] # temporary image to work with polygons", ":return: \"\"\" # save last 10 images img = self.paint_image.copy() self.backup.append(img) if len(self.backup)", "# in the paint mode, paint the event position self.save() self.draw(pos) def mouseReleaseEvent(self,", ":return: \"\"\" # erase all points from polygons for point_items in self.polygon_points: for", "self.set_label_text() paintmode_button.toggle() # complete the gui self.layout().addWidget(widget) self.layout().addWidget(self.view) if __name__ == \"__main__\": app", "self.paint_image = img self.scene.removeItem(self.paint_pixmap) self.paint_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(img)) def refresh_poly_image(self): self.scene.removeItem(self.poly_pixmap) self.poly_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image))", "point dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close\") ok =", "not needed self.mode = \"circles\" self.poly_button.setVisible(False) self.undo_button.setVisible(False) self.slider.setVisible(False) for button in self.color_buttons: button.setVisible(False)", "complete, drawing it\") # create the polygon polygon = QtGui.QPolygonF() for el in", "the arena) occultation_mask = np.array(img_arr[:,:,2], dtype=\"uint8\") # 2) set all pixels that contain", "QtGui.QPushButton(\"Outside of\\nthe arena\") red_button.setCheckable(True) red_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(red_button) self.color_buttons.append(red_button) eraser_button = QtGui.QPushButton(\"Eraser\") eraser_button.setCheckable(True) eraser_button.clicked.connect(self.switch_color) color_widget.layout().addWidget(eraser_button)", "Arena mask is now working with alpha data, but # TODO: occultation mask", "precision: print(\"Too close2\") ok = False if ok: self.point_items.append(self.pick_point(pos)) elif self.mode == \"paint\":", "everything not red is inside) # TODO: For some reason, color channels are", "pushed in paint mode, but affects polygon painting too (all polygons are saved", "add support for the original arena editor (circle) np.set_printoptions(threshold=np.nan) super(ArenaEditor, self).__init__() self.finish_callback =", "self.color == \"Eraser\": self.color = \"Hiding\\nplaces\" self.color_buttons[0].setChecked(True) self.color_buttons[2].setChecked(False) self.clear_button.setVisible(True) self.popup_button.setVisible(True) self.pen_label.setVisible(False) self.circle_label.setVisible(False) def", "self.scene.addPixmap(QtGui.QPixmap.fromImage(self.poly_image)) ########################## # CIRCLES MODE VARIABLES # ########################## # TODO: add circles mode", "to any other already chosen point dist = self.get_distance(pt, pos) if dist <", "polygons that are now changeable. :return: None \"\"\" # clear the canvas self.remove_items()", "= False for points in self.polygon_points: for pt in points: dist = self.get_distance(pt,", "size :param value: new pen size :return: None \"\"\" # change pen size", "self.background.shape[:2] for i in range(point.x() - self.pen_size/2, point.x() + self.pen_size/2): for j in", "start over :return: None \"\"\" self.remove_items() self.clear_poly_image() self.clear_paint_image() self.point_items = [] self.polygon_points =", "To extract mask data, only Red (0) and Blue (2) channels are needed.", "= self.sender().text() if self.DEBUG: print((\"Setting color to %s\" % text)) # make sure", "from PyQt4 import QtGui, QtCore import cv2 import sys import math import numpy", "# temporary image to work with circles self.circles_image = QtGui.QImage(bg_size, fmt) self.circles_image.fill(QtGui.qRgba(0, 0,", "from core.project.project import Project from gui.img_controls import gui_utils from gui.arena.my_ellipse import MyEllipse from", "places. Unresolvable colors will be considered red.\") widget.layout().addWidget(label) # SWITCH button and key", "points: dist = self.get_distance(pt, pos) if dist < precision: print(\"Too close2\") ok =", "user has chosen to be a future part of a polygon :param position:", "bool, whether the polygon was drawn \"\"\" # check if polygon can be", "painting too (all polygons are saved # as one step) self.backup = []", "in self.polygon_points: for point in point_items: self.scene.removeItem(point) # erase all independent points for", "brush.setStyle(QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(polygon) painter.end() # refresh the image self.refresh_poly_image() def repaint_polygons(self): \"\"\"", "tuple (arena_mask, occultation_mask) True in arena_masks means that the point is INSIDE the", "def refresh_circles_image(self): self.scene.removeItem(self.circles_pixmap) self.circles_pixmap = self.scene.addPixmap(QtGui.QPixmap.fromImage(self.circles_image)) def clear_paint_image(self): # remove all drawn lines" ]
[ "( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy,", "dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # Optional visualization # mod", "6), (3, 6), # linear astigmatism (1, 7), (1, 8) # constant coma", "time from scipy.optimize import least_squares import numpy as np import batoid import danish", "plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with", "# ) if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm() test_fitter_AuxTel_rigid_perturbation() test_dz_fitter_LSST_fiducial()", "field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs) guess = [0.0]*nstar + [0.0]*nstar +", "in data[1:niter]: thx = datum['thx'] thy = datum['thy'] z_ref = datum['z_ref'] z_actual =", "= ( (1, 4), # defocus (2, 4), (3, 4), # field tilt", "(2, 6), (3, 6), # linear astigmatism (1, 7), (1, 8) # constant", ") @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f:", "= fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(124)", "batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *=", "dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0", "try to recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 # We don't ship", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "= {rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f > 0.6\" % rms", "naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms = ( (1, 4),", "(3, 5), (2, 6), (3, 6), # linear astigmatism (1, 7), (1, 8)", "transverse Zernikes. Model and fitter run through the same code. \"\"\" # Nominal", "pixel_scale=20e-6 ) if __name__ == \"__main__\": niter = 10 else: niter = 2", "rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar", "imgs = fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter", "guess = [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3,", "*= wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66,", "(1, 8) # constant coma ) dz_true = np.empty(len(dz_terms)) for i, term in", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref =", "if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm() test_fitter_AuxTel_rigid_perturbation() test_dz_fitter_LSST_fiducial() test_dz_fitter_LSST_rigid_perturbation() test_dz_fitter_LSST_z_perturbation()", "mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength", "if __name__ == \"__main__\": niter = 10 else: niter = 1 for _", "fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point", "problematic. It has a large field angle, so flip based on # that.", "= rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope", "+ [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares( fitter.chi,", "np.array(z_fit) # mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) #", "sky_level=sky_level, flux=5e6 ) # Now guess aberrations are 0.0, and try to recover", "= 750e-9 rng = np.random.default_rng(2344) nstar = 10 if __name__ == \"__main__\": niter", "for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi,", "thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for", "dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit,", "'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner':", "M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy)", ") rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.6, \"rms", "{rms:9.3f} waves\") assert rms < 0.1, \"rms %9.3f > 0.1\" % rms #", "zernikes since danish uses a transverse aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope,", "Model and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb'", "binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level']", "Randomly perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5,", "i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out", "np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope,", "fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model(", "= data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "(3, 6), # linear astigmatism (1, 7), (1, 8), # constant coma (1,", "== \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm() test_fitter_AuxTel_rigid_perturbation() test_dz_fitter_LSST_fiducial() test_dz_fitter_LSST_rigid_perturbation() test_dz_fitter_LSST_z_perturbation() test_dz_fitter_LSST_kolm() test_dz_fitter_LSST_atm()", "fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA(", "= batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength = 750e-9", "fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8),", "thy=thy ) dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level", "= least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) )", "# linear astigmatism (1, 7), (1, 8) # constant coma ) dz_true =", "\"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10", "wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_terms = np.arange(4, 23) z_true", "np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for i, (thx,", ") dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms", "__name__ == \"__main__\": niter = 10 else: niter = 1 for _ in", "\"design\" zernikes. Use the transverse aberration # zernikes since danish uses a transverse", "np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66,", "mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm,", "np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12] # NOTE: The R_inner and focal_length", "run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f:", "= {rms:9.3f} waves\") assert rms < 0.4, \"rms %9.3f > 0.4\" % rms", "nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength,", "%9.3\" % (rms1x1, tol) # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength,", "I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "(1, 21), (1, 22) ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms):", "rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\"", "in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 =", "%9.3f > 0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere", "telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\",", "zernikes. Use the transverse aberration # zernikes since danish uses a transverse aberration", "to despace M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\",", "2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i,", "np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use the transverse aberration # zernikes since", "with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) sky_level", "= [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result =", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 23): out", "factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19", "nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_terms = np.arange(4, 23)", "1000.0 # counts per pixel # Make a test image using true aberrations", "np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f", "reference \"design\" zernikes. Use the transverse aberration # zernikes since danish uses a", "rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms", "dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now guess aberrations are 0.0, and", "[cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a =", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs", "import danish from test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner':", "= (z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs) guess = [0.0]*nstar +", ") nstar = len(thxs) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms)", "z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms", "c='r', label='fit - truth' ) if ylim is None: ylim = -0.6, 0.6", "mod, z_fit/wavelength, z_true/wavelength) # One fit is problematic. It has a large field", "rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\",", "M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy,", "ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11,", "fluxes = [5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes )", "jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2", "+ [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3,", "batoid import danish from test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii = {", "= rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx,", "reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120,", "1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576,", "131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515,", "sky_level = data[0]['sky_level'] if __name__ == \"__main__\": niter = 10 else: niter =", "naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms = np.arange(4, 12) z_true", "double Zernike offsets. Model and fitter run through the same code. \"\"\" telescope", "{rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen", "ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' )", "fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true),", "%9.3f > %9.3\" % (rms1x1, tol) # Try binning 2x2 binned_fitter = danish.SingleDonutModel(", "fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(1234) if", "> 0.6\" % rms # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength,", "= rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer,", "danish uses a transverse aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy,", "= len(z_fit)+4 import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs =", "out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit =", "batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *=", "+ [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac,", "dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx,", "10 else: niter = 2 for _ in range(niter): # Randomly perturb M2", "% rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce test", "fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 <", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to make test images", "cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16]", "% rms # dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods = fitter.model(", "11), # constant spherical (1, 12), (1, 13), # second astigmatism (1, 14),", "test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid to produce test image of", "rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce test images", "8) # constant coma ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms):", "= datum['thx'] thy = datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual'] img =", "binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time()", "dy = 0.0, 0.0 fwhm = 0.7 sky_level = 1000.0 img = fitter.model(", "guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi,", "dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy", "# mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img,", "fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19", "args=(img, sky_level) ) for i in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out", "jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for", "(rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\")", "0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx,", ") z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61", "pixel # Make a test image using true aberrations img = fitter.model( dx,", "z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61", "23) z_true = (z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18,", "fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result =", "least_squares import numpy as np import batoid import danish from test_helpers import timer", "using danish model to produce a test image with fiducial LSST transverse Zernikes", "wavelength dz_terms = ( (1, 4), # defocus (2, 4), (3, 4), #", "rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\"", "enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8),", "pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level =", "fluxes = [5e6]*nstar imgs = fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes )", "waves\") assert rms < 0.6, \"rms %9.3f > 0.6\" % rms @timer def", "def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of rigid-body", "# mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results(", "rms < 0.6, \"rms %9.3f > 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip", "spherical (1, 12), (1, 13), # second astigmatism (1, 14), (1, 15) #", "rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "1.7: tol = 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit,", "rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase", "225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii", "guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in", "batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside 0.05 degree radius field-of-view thr =", "LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138,", "thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120,", "z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f >", "fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05)", "focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual", "with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) wavelength", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i", "jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength,", "6), (3, 6), # linear astigmatism (1, 7), (1, 8), # constant coma", "rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1,", "\"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model", "size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope =", "[0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs,", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms =", "true aberrations img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) #", "11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = {", "out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit", "0.0008] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter", "0.0, 0.0 fwhm = 0.7 sky_level = 1000.0 img = fitter.model( dx, dy,", "Model and fitter run through the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys", "= rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic(", "\"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) wavelength = data[0]['wavelength'] factory =", "= binned_result.x z_fit = np.array(z_fit) # mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit,", "dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true,", "cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23]", "< 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip", "\"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9,", "= danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0", "= 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter = 10 else:", "\"__main__\": niter = 10 else: niter = 2 for datum in data[1:niter]: thx", "It has a large field angle, so flip based on # that. if", "fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with DOF to optimize... fitter", "rms < 0.05, \"rms %9.3f > 0.05\" % rms # dxs_fit, dys_fit, fwhm_fit,", "pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory(", "waves\") assert rms < 0.1, \"rms %9.3f > 0.1\" % rms # mods", ":]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit')", "data[0]['sky_level'] if __name__ == \"__main__\": niter = 10 else: niter = 2 for", "# NOTE: The R_inner and focal_length here don't quite match what I've #", "thxs=thxs, thys=thys ) nstar = len(thxs) guess = [0.0]*nstar + [0.0]*nstar + [0.7]", "here don't quite match what I've # seen elsewhere. Possible location for future", "field tilt (2, 5), (3, 5), (2, 6), (3, 6), # linear astigmatism", "ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax),", ".withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic(", "%9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time:", "run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f:", "5), (2, 6), (3, 6), # linear astigmatism (1, 7), (1, 8), #", "= fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod))", "[0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\":", "np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter =", "fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength)", "= [] imgs = [] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual'])", ") dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level =", "np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms", "1 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz =", "verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out", "import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3)", "batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] =", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength #", "M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz])", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__", "aberrations are 0.0, and try to recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8", "# dxs_fit, dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results( # imgs, mods, dz_fit/wavelength,", "for i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel(", "M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy =", "AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit, z_true, ylim=None): jmax", "z_terms=z_terms, thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5,", "= rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic(", ") .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10", "sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18,", "atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms", "optics. Model and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"),", "M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0,", "%9.3f > 0.1\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit,", "ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish", "thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4), # defocus", "import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3)", "tol = 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true,", "to produce test images with fiducial LSST transverse Zernikes plus random double Zernike", "dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms =", "dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb =", "*= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) #", ") wavelength = 750e-9 rng = np.random.default_rng(124) if __name__ == \"__main__\": niter =", "batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9,", "np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66,", ") z_refs *= wavelength dz_terms = ( (1, 4), # defocus (2, 4),", "5), (3, 5), (2, 6), (3, 6), # linear astigmatism (1, 7), (1,", "to produce a test images of rigid-body perturbed LSST transverse Zernikes. Model and", "data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "One fit is problematic. It has a large field angle, so flip based", "% rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test", "perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5)", "images with fiducial LSST transverse Zernikes plus random double Zernike offsets. Model and", "np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength)", "__name__ == \"__main__\": niter = 10 else: niter = 2 for datum in", "[cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr =", "# plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms =", "mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2])", "naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength # The zernikes of the", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = (", "fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2)", "thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares(", "telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength", "z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit,", "if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit,", "0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert", "= danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5,", "def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data =", "match what I've # seen elsewhere. Possible location for future improvement. factory =", "def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid to produce test image", "test image of AOS DOF perturbed optics. Model and fitter run independent code.", "pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy", "12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in enumerate(zip(imgs, mods)): ax0", "= rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5,", "fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5,", "cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph =", "i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory", "kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66,", "= {rms:9.3f} waves\") assert rms < 0.2, \"rms %9.3f > 0.2\" % rms", "0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a", "# dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(", "plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1 =", "tol) # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy,", "z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0,", "test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802,", "for i, (img, mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 =", "10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion", "max_nfev=20, verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23):", "rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # ) #", "wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit =", "in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs,", "1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs", "rms < 0.6, \"rms %9.3f > 0.6\" % rms # Try binning 2x2", "dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms)", "label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms)", "factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel(", "(dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys )", "{ 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod,", "= rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope", "The zernikes of the perturbed telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope,", "fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit is", "t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) #", "constant spherical (1, 12), (1, 13), # second astigmatism (1, 14), (1, 15)", "in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms,", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 23):", "%9.3f > 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to", "'rb' ) as f: data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength']", "dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb'", "sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess,", "0.6\" % rms # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms,", ") M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope", "= { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit, z_true, ylim=None): jmax =", "16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567,", "import numpy as np import batoid import danish from test_helpers import timer directory", "atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert", "\"rms %9.3f > 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model", "= np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66,", "atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.1,", "out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out)", "as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0 =", "nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar)", "verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength,", "R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms,", "test images of rigid-body perturbed LSST transverse Zernikes. Model and fitter run through", "= fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0,", "thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph))", "thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares( binned_fitter.chi,", "thxs=thxs, thys=thys ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result", "[M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside 0.05", "- truth' ) if ylim is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike", "optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess =", "10 else: niter = 2 for datum in data[1:niter]: thx = datum['thx'] thy", "12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\"", "0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter =", "np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\")", "= 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0,", "= np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f > %9.3\" % (rms1x1, tol)", "wavelength z_terms = np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23] factory = danish.DonutFactory(", "= data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory", "(3, 4), # field tilt (2, 5), (3, 5), (2, 6), (3, 6),", "np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2", "% rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test", "if __name__ == \"__main__\": niter = 10 else: niter = 2 for _", "10), # constant trefoil (1, 11), # constant spherical (1, 12), (1, 13),", "ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\"", "least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1", "rms < 0.1, \"rms %9.3f > 0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip", "range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys", "]) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0,", "wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = [] thys", "thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys =", "waves\") assert rms < 0.05, \"rms %9.3f > 0.05\" % rms # dxs_fit,", "test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f)", "dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now guess aberrations are 0.0,", "dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2))", "data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = [] thys = [] z_refs = []", "\"__main__\": niter = 10 else: niter = 2 for _ in range(niter): thr", "(1, 18), (1, 19), (1, 20), (1, 21), (1, 22) ) dz_true =", "= fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar +", "M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph", "image of AOS DOF perturbed optics. Model and fitter run independent code. \"\"\"", "1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model( dxs, dys, fwhm,", "factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel(", "= fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength = 750e-9 rng = np.random.default_rng(234)", "with fiducial LSST transverse Zernikes plus random Zernike offsets. Model and fitter run", "z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy = 0.0, 0.0 fwhm =", "# Now guess aberrations are 0.0, and try to recover truth. guess =", "rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model( dxs, dys,", "\"\"\" # Nominal donut mode for AuxTel is to despace M2 by 0.8", "plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img,", "*z_fit = binned_result.x z_fit = np.array(z_fit) # mod = binned_fitter.model( # dx_fit, dy_fit,", "jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope,", "13), # second astigmatism (1, 14), (1, 15) # quatrefoil ) dz_true =", "< 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using", "< 2*tol, \"rms %9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time:", "constant trefoil (1, 11), # constant spherical (1, 12), (1, 13), # second", "# linear astigmatism (1, 7), (1, 8), # constant coma (1, 9), (1,", "= fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i,", "sky_level) ) t1 = time.time() t1x1 = t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength", "obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255", "(1, 7), (1, 8) # constant coma ) dz_true = np.empty(len(dz_terms)) for i,", "'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion =", "thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar)", "imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory,", "plus random Zernike offsets. Model and fitter run through the same code. \"\"\"", "plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with", "size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy", ") guess = [0.0, 0.0, 0.7] + [0.0]*19 t0 = time.time() result =", "data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = [] thys = []", ") ) # Random point inside 0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0,", ".withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a", "= danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7]", "== \"__main__\": niter = 10 else: niter = 1 for _ in range(niter):", "= {rms:9.3f} waves\") assert rms < 0.1, \"rms %9.3f > 0.1\" % rms", "z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit,", "focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx,", "4), # defocus (2, 4), (3, 4), # field tilt (2, 5), (3,", "rms < 0.2, \"rms %9.3f > 0.2\" % rms # mods = fitter.model(", "fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength", "(1, 14), (1, 15) # quatrefoil ) dz_true = np.empty(len(dz_terms)) for i, term", "fitter with DOF to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs,", ") # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__", "rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5)", "counts per pixel # Make a test image using true aberrations img =", "plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2))", "= data[0]['sky_level'] if __name__ == \"__main__\": niter = 10 else: niter = 2", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to make test", "# plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__ ==", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref", "model to produce a test image of rigid-body perturbed LSST transverse Zernikes. Model", "= { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance':", "telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\",", "\"rms %9.3f > 0.05\" % rms # dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x)", "sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4)", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb =", "through the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0,", "waves\") assert rms < 0.6, \"rms %9.3f > 0.6\" % rms # Try", "thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4), # defocus (2,", "rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs", "dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs", "fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0,", "fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2", "z_refs *= wavelength dz_terms = ( (1, 4), # defocus (2, 4), (3,", "code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] )", "0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a", "ship a custom fitting algorithm; just use scipy.least_squares result = least_squares( fitter.chi, guess,", "despace M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0,", "assert rms2x2 < 2*tol, \"rms %9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1", "18), (1, 19), (1, 20), (1, 21), (1, 22) ) dz_true = np.empty(len(dz_terms))", "= np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter", "%9.3f > 0.2\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit,", "= [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess,", "batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 =", "f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) #", "args=(img, sky_level) ) for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out", "z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0,", "_ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar)", "%9.3f > 0.6\" % rms # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory,", "atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.02\" %", "{result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit,", "# Toy zfitter to make test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(),", "sky_level = 1000.0 # counts per pixel # Make a test image using", "801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115", "M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside 0.05 degree radius", "niter = 10 else: niter = 2 for _ in range(niter): thr =", "= np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA(", "as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "rigid-body perturbed LSST transverse Zernikes. Model and fitter run through the same code.", "Kolmogorov profile sky_level = 1000.0 # counts per pixel # Make a test", "= np.random.default_rng(234) if __name__ == \"__main__\": niter = 10 else: niter = 2", "rng = np.random.default_rng(124) if __name__ == \"__main__\": niter = 10 else: niter =", "z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys =", "= len(thxs) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels =", "z_fit = np.array(z_fit) # Optional visualization # mod = fitter.model( # dx_fit, dy_fit,", "2*tol, \"rms %9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f}", "assert rms < 0.6, \"rms %9.3f > 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation():", "jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4,", "jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "time.time() t2x2 = t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit", "+ [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3,", "ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot", "eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66,", "mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12))", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\": niter = 10", "focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys )", "else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1", ") fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy", "# dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit,", "(1, 19), (1, 20), (1, 21), (1, 22) ) dz_true = np.empty(len(dz_terms)) for", "atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert", "= rng.uniform(0.5, 1.5) sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true,", "z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result", "15), # quatrefoil (1, 16), (1, 17), (1, 18), (1, 19), (1, 20),", "1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm,", "> 0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere +", "np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike(", "rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\"", "z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 )", "+ [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "and focal_length here don't quite match what I've # seen elsewhere. Possible location", "fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2))", "1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA(", "2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope", "rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10,", ".withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) )", "(2, 5), (3, 5), (2, 6), (3, 6), # linear astigmatism (1, 7),", "dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to", "what I've # seen elsewhere. Possible location for future improvement. factory = danish.DonutFactory(", "fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar", "# ) @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as", "0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\":", "mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\",", "0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter", "2 for _ in range(niter): # Randomly perturb M2 alignment M2_dx, M2_dy =", "the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015])", "truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 # We don't ship a custom fitting", "danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = 0.0, 0.0 fwhm", "= 0.7 sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level,", "inside 0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi)", "plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__ == \"__main__\":", "dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar =", "(1, 13), # second astigmatism (1, 14), (1, 15), # quatrefoil (1, 16),", "fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def", "Random point inside 0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph =", "1 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0,", "factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar + [0.0]*nstar +", "batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *=", "is to despace M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic(", "(2, 6), (3, 6), # linear astigmatism (1, 7), (1, 8), # constant", "dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a", "dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms", "astigmatism (1, 7), (1, 8), # constant coma (1, 9), (1, 10), #", "t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod =", "image of rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes. Model and fitter run", "uses a transverse aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength,", "a large field angle, so flip based on # that. if np.rad2deg(np.hypot(thx, thy))", "label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth' ) if ylim is", "7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912,", "8) # constant coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory(", "-0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def", "10 else: niter = 1 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2,", "to produce a test image of rigid-body perturbed LSST transverse Zernikes. Model and", "[0.0]*19 t0 = time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "= fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0,", "= np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar", "0.7] + [0.0]*19 t0 = time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3,", "danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 =", "= rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3,", "np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61", "0.7 # Arcsec for Kolmogorov profile sky_level = 1000.0 # counts per pixel", "matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit =", "7)) gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1])", "fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5,", "of AOS DOF perturbed optics. Model and fitter run independent code. \"\"\" with", "for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx,", "niter = 2 for _ in range(niter): # Randomly perturb M2 alignment M2_dx,", "# dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2,", "= datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms", "53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201,", "size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter =", "R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx,", "'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit':", "= fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(1234)", "plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt fig =", "produce test images with fiducial LSST transverse Zernikes plus random double Zernike offsets.", "nstar = len(thxs) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels", "z_refs *= wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10,", "(3, 5), (2, 6), (3, 6), # linear astigmatism (1, 7), (1, 8),", "zernikes of the perturbed telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx,", "0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength)", ") ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11)", "dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0,", "c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6,", "rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "produce a test image of rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes. Model", "# Actual fitter with DOF to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms,", "np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.05, \"rms %9.3f > 0.05\"", "# dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\": niter = 10 else: niter", "4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076,", "def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of rigid-body", "fwhm = 0.7 # Arcsec for Kolmogorov profile sky_level = 1000.0 # counts", "= [0.0, 0.0, 0.7]+[0.0]*8 # We don't ship a custom fitting algorithm; just", "with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory", "fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img)", "alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth'", "= rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0 img =", "2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy)", "large field angle, so flip based on # that. if np.rad2deg(np.hypot(thx, thy)) >", "= batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb", "telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength", "dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"),", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx,", "z_true/wavelength) # One fit is problematic. It has a large field angle, so", "dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength", "dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength,", "niter = 2 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph =", "@timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test images of", "z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit,", "'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance':", "0.0 fwhm = 0.7 sky_level = 1000.0 img = fitter.model( dx, dy, fwhm,", "< 0.6, \"rms %9.3f > 0.6\" % rms # Try binning 2x2 binned_fitter", "batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope,", "np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1", "rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f", "= telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface(", "::-1]) dz_terms = ( (1, 4), # defocus (2, 4), (3, 4), #", "batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *=", "AuxTel is to despace M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope =", "eps=0.61 ) z_refs *= wavelength dz_terms = ( (1, 4), # defocus (2,", "fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0,", "20), (1, 21), (1, 22) ) dz_true = np.empty(len(dz_terms)) for i, term in", "{ 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589,", "M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([", "np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f > %9.3\" % (rms1x1, tol) #", "879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion", "{t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\")", "0.0, 0.0 fwhm = 0.7 # Arcsec for Kolmogorov profile sky_level = 1000.0", "rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength,", "\"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344)", "image using true aberrations img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6", "(1, 4), # defocus (2, 4), (3, 4), # field tilt (2, 5),", "z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f >", "R_inner and focal_length here don't quite match what I've # seen elsewhere. Possible", "and fitter run through the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope =", "batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10 thr", "= danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5, 0.5,", "LSST transverse Zernikes plus random double Zernike offsets. Model and fitter run through", "of rigid-body perturbed LSST transverse Zernikes. Model and fitter run through the same", "test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test images of rigid-body perturbed", "- z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter", "fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0,", "(z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img))", "# constant coma (1, 9), (1, 10), # constant trefoil (1, 11), #", ") as f: data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm", "M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy =", "%9.3f > 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to", "plot_result(img, mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as plt fig", "= data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs =", "# plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation():", "'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance':", "'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer':", "wavelength z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory(", "test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of rigid-body +", "M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz", ") z_perturb *= wavelength z_terms = np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23]", "M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside 0.05 degree", "max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 23): out = f\"{i:2d}", "20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner )", "ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img))", "time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit", "eps=0.61 ) z_perturb *= wavelength z_terms = np.arange(4, 23) z_true = (z_perturb -", "5), (2, 6), (3, 6), # linear astigmatism (1, 7), (1, 8) #", "z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4), # defocus (2, 4),", "@timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data", "dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar +", "0.6, \"rms %9.3f > 0.6\" % rms # Try binning 2x2 binned_fitter =", "time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img,", "t1 = time.time() t2x2 = t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit =", "make test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys )", ") t1 = time.time() t2x2 = t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit", "as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i,", "danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy = 0.0, 0.0", "750e-9 rng = np.random.default_rng(124) if __name__ == \"__main__\": niter = 10 else: niter", "ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0,", "cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4,", "= [0.0, 0.0, 0.7] + [0.0]*19 t0 = time.time() result = least_squares( fitter.chi,", "print(f\"rms = {rms:9.3f} waves\") assert rms < 0.2, \"rms %9.3f > 0.2\" %", "sky_levels = [sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", ".withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2 =", "coma (1, 9), (1, 10), # constant trefoil (1, 11), # constant spherical", "np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4)", "telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms = ( (1, 4),", "jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength # The zernikes of the perturbed telescope.", "'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance':", "{rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f > 0.6\" % rms #", "rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms = ( (1, 4), # defocus (2,", "= 10 else: niter = 1 for _ in range(niter): M2_dx, M2_dy =", "telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ ==", "a test image using true aberrations img = fitter.model( dx, dy, fwhm, z_true,", "(thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20,", "z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img)", "with fiducial LSST transverse Zernikes plus random double Zernike offsets. Model and fitter", "datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter", "67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx,", "# seen elsewhere. Possible location for future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115,", "rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid to produce", "ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce", "R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx,", "\"\"\"Roundtrip using danish model to produce a test image of rigid-body perturbed AuxTel", "batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar =", "2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1)", "rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes. Model and fitter run through the", "args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0,", "[0.0, 0.0, 0.7]+[0.0]*8 # We don't ship a custom fitting algorithm; just use", "assert rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial():", "np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.02\" % rms @timer def", "= rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5,", "750e-9 rng = np.random.default_rng(2344) nstar = 10 if __name__ == \"__main__\": niter =", "plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in enumerate(zip(imgs,", ") dx, dy = 0.0, 0.0 fwhm = 0.7 # Arcsec for Kolmogorov", "# Arcsec for Kolmogorov profile sky_level = 1000.0 # counts per pixel #", "@timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of", "= 1 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph =", "rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.05, \"rms %9.3f", "data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4), #", "Possible location for future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8,", "batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *=", ") z_ref *= wavelength # The zernikes of the perturbed telescope. I.e., the", "np.array(z_fit) # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) #", "z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert", "aberration # zernikes since danish uses a transverse aberration ray-hit model. z_ref =", "= rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref,", "0.4\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit #", ") ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7)", "danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] +", "R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar))", "dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit,", "'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit':", "[0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3,", "Zernike offsets. Model and fitter run through the same code. \"\"\" telescope =", "verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit,", "3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope", "wavelength = 750e-9 rng = np.random.default_rng(2344) nstar = 10 if __name__ == \"__main__\":", "750e-9 rng = np.random.default_rng(1234) if __name__ == \"__main__\": niter = 10 else: niter", "\"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength", "rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.02\" % rms", "750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter = 10 else: niter", "dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0,", "fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2))", "M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0,", "fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength =", "10 if __name__ == \"__main__\": niter = 10 else: niter = 1 for", "if __name__ == \"__main__\": niter = 10 else: niter = 2 for datum", "Optional visualization # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # )", "thy=thy, npix=255 ) dx, dy = 0.0, 0.0 fwhm = 0.7 # Arcsec", "= np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface,", "} def plot_result(img, mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as", "[] thys = [] z_refs = [] z_actuals = [] imgs = []", "images of rigid-body perturbed LSST transverse Zernikes. Model and fitter run through the", "fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 =", "range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)),", "# Optional visualization # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit #", "ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7))", "\"\"\" Roundtrip using danish model to produce test images with fiducial LSST transverse", "factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel(", "rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner", "telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength", "= {rms:9.3f} waves\") assert rms < 0.05, \"rms %9.3f > 0.05\" % rms", "+ [0.0]*19 t0 = time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3,", "} AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 }", "rms2x2 < 2*tol, \"rms %9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit", "22) ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term]", "23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\"", "result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level)", "[0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares( fitter.chi, guess,", "[M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\",", "= [0.0, 0.0, 0.7] + [0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3,", "- z_ref)[4:12] # NOTE: The R_inner and focal_length here don't quite match what", "ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax),", "ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :])", ") @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f:", "t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit =", "danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5, 0.5, size=2)", "= batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng =", "mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 =", "astigmatism (1, 14), (1, 15) # quatrefoil ) dz_true = np.empty(len(dz_terms)) for i,", "data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory =", "2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs =", "and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' )", "danish model to produce test images with fiducial LSST transverse Zernikes plus random", "+ [0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial():", "= 750e-9 rng = np.random.default_rng(1234) if __name__ == \"__main__\": niter = 10 else:", "= 2 for _ in range(niter): # Randomly perturb M2 alignment M2_dx, M2_dy", "fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit)", "the perturbed telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength,", ") # Toy zfitter to make test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs,", "test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of rigid-body perturbed", ") if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm() test_fitter_AuxTel_rigid_perturbation() test_dz_fitter_LSST_fiducial() test_dz_fitter_LSST_rigid_perturbation()", "(Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref,", "niter = 10 else: niter = 2 for datum in data[1:niter]: thx =", "z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for i, (thx, thy) in", "dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm()", "def plot_result(img, mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as plt", "a test image of rigid-body perturbed LSST transverse Zernikes. Model and fitter run", "'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit':", "guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result", "sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model( dxs, dys, fwhm, dz_true,", "guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1 = time.time()", "test image of rigid-body perturbed LSST transverse Zernikes. Model and fitter run through", "Model and fitter run through the same code. \"\"\" # Nominal donut mode", "= telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr", "z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *=", "54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727,", "'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer':", "nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms = np.arange(4, 23)", "code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength =", "test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of rigid-body perturbed", "\"rms %9.3f > %9.3\" % (rms1x1, tol) # Try binning 2x2 binned_fitter =", "\"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx,", "image of rigid-body perturbed LSST transverse Zernikes. Model and fitter run through the", "factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys", "%9.3f > 0.05\" % rms # dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) #", "M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope =", "# One fit is problematic. It has a large field angle, so flip", "= 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs,", "dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms", "13), # second astigmatism (1, 14), (1, 15), # quatrefoil (1, 16), (1,", "rng = np.random.default_rng(234) if __name__ == \"__main__\": niter = 10 else: niter =", "20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner )", "independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data", "= data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = [] thys = [] z_refs =", "coma ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term]", "rng.uniform(0.5, 1.5) sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level,", "focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\": niter = 10 else: niter =", "*= wavelength z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory =", "GalSim phase screen atmosphere + batoid to produce test image of AOS DOF", "\"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(1234) if __name__", "np import batoid import danish from test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii", "len(thxs) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar", "imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation()", "model to produce test images with fiducial LSST transverse Zernikes plus random double", "2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262,", "= [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels,", "2 for datum in data[1:niter]: thx = datum['thx'] thy = datum['thy'] z_ref =", "fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results( # imgs, mods,", ") M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope", "rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy,", "= data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory", "factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level']", "reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy,", "= np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.2, \"rms %9.3f >", "gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs,", "dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5,", "jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms = np.arange(4, 23) z_true = (z_perturb", "\"rms %9.3f > 0.4\" % rms # mods = fitter.model( # dxs_fit, dys_fit,", "fitter run through the same code. \"\"\" # Nominal donut mode for AuxTel", "telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) )", "code. \"\"\" # Nominal donut mode for AuxTel is to despace M2 by", "M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a,", "# field tilt (2, 5), (3, 5), (2, 6), (3, 6), # linear", "nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms = np.arange(4, 12)", "z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 )", "factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs) guess = [0.0]*nstar", "nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms = ( (1,", "\"__main__\": niter = 10 else: niter = 2 for _ in range(niter): M2_dx,", "guess = [0.0, 0.0, 0.7] + [0.0]*19 t0 = time.time() result = least_squares(", "ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def", "transverse Zernikes. Model and fitter run through the same code. \"\"\" fiducial_telescope =", "img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now guess", "danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar)", "( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random", "atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f}", "AuxTel transverse Zernikes. Model and fitter run through the same code. \"\"\" #", "LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365,", "Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip", "z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True,", "sky_level) ) for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out +=", "= pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(1234) if __name__ == \"__main__\":", "thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20,", "ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4,", "dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength,", "rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip", "dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to", "dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' )", "sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys,", "= [5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) #", "pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual =", "else: niter = 1 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4,", "cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2,", "fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = 0.0,", ") t1 = time.time() t1x1 = t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for", "0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) -", "\"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18,", "R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi)", "thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120,", "# quatrefoil ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] =", "dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] +", "guess = [0.0, 0.0, 0.7]+[0.0]*8 # We don't ship a custom fitting algorithm;", "'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 }", "fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with DOF", "model to produce a test image with fiducial LSST transverse Zernikes plus random", "# constant spherical (1, 12), (1, 13), # second astigmatism (1, 14), (1,", "} AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit, z_true, ylim=None):", "np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine", "0.0, 0.7] + [0.0]*19 t0 = time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac,", "wavelength = 750e-9 rng = np.random.default_rng(1234) if __name__ == \"__main__\": niter = 10", "independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data", "np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f", "danish model to produce a test image of rigid-body perturbed AuxTel transverse Zernikes.", "dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength,", "z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f}", "# ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit is problematic. It", "atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.2,", "atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0,", "for AuxTel is to despace M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope", "jmax = len(z_fit)+4 import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs", "fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0,", "np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61", "*z_fit = result.x z_fit = np.array(z_fit) # mod = fitter.model( # dx_fit, dy_fit,", "(thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20,", "test image with fiducial LSST transverse Zernikes plus random Zernike offsets. Model and", ") dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 )", "code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data =", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1 = time.time() t1x1 = t1", "focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 )", "run through the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0,", "M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a,", "transverse Zernikes plus random double Zernike offsets. Model and fitter run through the", "= fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms =", "2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx,", "in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy =", "- dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "= 1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess", "thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61", "0.7 sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6", "jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true),", "to produce a test image with fiducial LSST transverse Zernikes plus random Zernike", "z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10,", "0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs,", "jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1 = time.time() t1x1", "fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength =", ") rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.1, \"rms", "= 2 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0,", "telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344) nstar", "0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a", "= [] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms", "test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce test images with fiducial LSST", "ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b',", "Make a test image using true aberrations img = fitter.model( dx, dy, fwhm,", "assert rms < 0.1, \"rms %9.3f > 0.1\" % rms # mods =", "Use the transverse aberration # zernikes since danish uses a transverse aberration ray-hit", "(1, 7), (1, 8), # constant coma (1, 9), (1, 10), # constant", "mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2", "ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double", "rms < 0.4, \"rms %9.3f > 0.4\" % rms # mods = fitter.model(", "atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\" %", "'rb' ) as f: data = pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory(", "batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph =", "to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess", "data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "= np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer", "0.0, and try to recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 # We", "= 10 else: niter = 1 for _ in range(niter): thr = np.sqrt(rng.uniform(0,", "term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory =", "z_refs = [] z_actuals = [] imgs = [] for datum in data[1:]:", "ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce a", "\"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength", "with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory", "size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope =", "dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # Optional visualization #", "on # that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7 else: tol", "\"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength =", "Zernikes plus random double Zernike offsets. Model and fitter run through the same", "print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere", "'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance':", "wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb", "reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms = np.arange(4, 23) z_true =", "nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs =", ") wavelength = 750e-9 rng = np.random.default_rng(1234) if __name__ == \"__main__\": niter =", "[sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs,", "::-1] z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy", "ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx,", "of rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes. Model and fitter run through", "thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i, (thx, thy) in", "thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i, (thx, thy)", "for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy,", "= np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs,", "= least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) )", "np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"),", "thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 t0 = time.time()", "range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\"", "= plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in", "gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(", "Zernikes plus random Zernike offsets. Model and fitter run through the same code.", "thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61", "np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess =", "z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4), # defocus (2, 4), (3,", "ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend()", "perturbed AuxTel transverse Zernikes. Model and fitter run through the same code. \"\"\"", "plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0,", "Determine reference \"design\" zernikes. Use the transverse aberration # zernikes since danish uses", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2 fit", "0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(1234) if __name__ == \"__main__\": niter", "*= wavelength z_terms = np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12] # NOTE:", "-2.7000030360993734 } def plot_result(img, mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot", "test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere + batoid to produce test image", "rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner", "in range(niter): # Randomly perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2)", "plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10,", "2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength,", "in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory(", "np.random.default_rng(124) if __name__ == \"__main__\": niter = 10 else: niter = 1 for", "run through the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\",", "t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\"", "0.4, \"rms %9.3f > 0.4\" % rms # mods = fitter.model( # dxs_fit,", "time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img,", "fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1,", "dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0,", "*= wavelength dz_terms = ( (1, 4), # defocus (2, 4), (3, 4),", "using danish model to produce a test image of rigid-body + M1-surface-Zernike perturbed", "\"\"\" Roundtrip using danish model to produce a test image with fiducial LSST", "= (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level", "\"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(124) if __name__", "# plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm():", "# that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7 else: tol =", "% rms # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx,", "'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion =", "= fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot(", "reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike(", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy )", "M1-surface-Zernike perturbed LSST transverse Zernikes. Model and fitter run through the same code.", "datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx,", "M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy =", "np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i]", "None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int))", "size=2) fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0 img = fitter.model( dx, dy,", "np.random.default_rng(1234) if __name__ == \"__main__\": niter = 10 else: niter = 1 for", "rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\",", "ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt fig", "(2, 4), (3, 4), # field tilt (2, 5), (3, 5), (2, 6),", "are 0.0, and try to recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 #", "z_perturb *= wavelength z_terms = np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23] factory", "# quatrefoil (1, 16), (1, 17), (1, 18), (1, 19), (1, 20), (1,", "code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data =", "*= wavelength z_terms = np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23] factory =", "I've # seen elsewhere. Possible location for future improvement. factory = danish.DonutFactory( R_outer=0.6,", "0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(124) if __name__ == \"__main__\":", "# Determine reference \"design\" zernikes. Use the transverse aberration # zernikes since danish", "tilt (2, 5), (3, 5), (2, 6), (3, 6), # linear astigmatism (1,", "z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 result", "( (1, 4), # defocus (2, 4), (3, 4), # field tilt (2,", "mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model", "= [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels,", "dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' )", "= fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # )", ") # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms", "from scipy.optimize import least_squares import numpy as np import batoid import danish from", "LSST transverse Zernikes plus random Zernike offsets. Model and fitter run through the", "fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f}", "rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test image", "a test image of rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes. Model and", "0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish", "= fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit,", "max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2 = t1 - t0", "z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 result =", ") # Now guess aberrations are 0.0, and try to recover truth. guess", "constant coma ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] =", "data[0]['dz_actual'] thxs = [] thys = [] z_refs = [] z_actuals = []", "args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2)", "nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope,", "= 750e-9 rng = np.random.default_rng(124) if __name__ == \"__main__\": niter = 10 else:", "import pickle import time from scipy.optimize import least_squares import numpy as np import", "[0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957,", "niter = 1 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2)", "(1, 8), # constant coma (1, 9), (1, 10), # constant trefoil (1,", "fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength,", "z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5", "= [] z_refs = [] z_actuals = [] imgs = [] for datum", "dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19 result", "= [] thys = [] z_refs = [] z_actuals = [] imgs =", "wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter = 10", "0.1\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit #", "0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] )", "dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to make test images fitter0", "(img, mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1])", "4), (3, 4), # field tilt (2, 5), (3, 5), (2, 6), (3,", "- mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k',", "run through the same code. \"\"\" # Nominal donut mode for AuxTel is", "# ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test", "c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike", "else: niter = 1 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar))", "# The zernikes of the perturbed telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA(", "1.5) sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6", "binned_result.x z_fit = np.array(z_fit) # mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit", "dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit", ") rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.4, \"rms", "dz_terms # ) if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm() test_fitter_AuxTel_rigid_perturbation()", "= np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f >", "# plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation():", "(dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 )", "images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs =", "thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67))", "0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0 img = fitter.model( dx,", "fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength = 750e-9 rng = np.random.default_rng(234) if", "_ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy", "to produce a test image of rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes.", "@timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce test images with", "7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ])", "test image using true aberrations img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level,", "= fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0,", "dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt", "os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) wavelength = data[0]['wavelength']", "_ in range(niter): # Randomly perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4,", "ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true,", "assert rms1x1 < 2*tol, \"rms %9.3f > %9.3\" % (rms1x1, tol) # Try", "print(f\"rms = {rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f > 0.6\" %", "0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference", "telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120,", "recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 # We don't ship a custom", "eps=0.61 ) dz_terms = ( (1, 4), # defocus (2, 4), (3, 4),", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if", "(1, 15) # quatrefoil ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms):", "z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 )", "jmax=66, eps=0.61 ) dz_terms = ( (1, 4), # defocus (2, 4), (3,", "rms1x1 < 2*tol, \"rms %9.3f > %9.3\" % (rms1x1, tol) # Try binning", "eps=0.61 ) z_refs *= wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8),", "= datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23)", "that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7 else: tol = 0.25", "rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\" % rms", "datum in data[1:niter]: thx = datum['thx'] thy = datum['thy'] z_ref = datum['z_ref'] z_actual", "0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid", "fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as", "dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms =", "ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar,", "__name__ == \"__main__\": niter = 10 else: niter = 2 for _ in", "fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i", "\"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside 0.05 degree radius field-of-view thr", "f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit,", "'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance':", "# plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms =", "npix=255 ) dx, dy = 0.0, 0.0 fwhm = 0.7 # Arcsec for", "fiducial LSST transverse Zernikes plus random Zernike offsets. Model and fitter run through", "0.7] + [0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", "algorithm; just use scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2)", "[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img,", "{ 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324,", "z_ref = datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms = np.arange(4,", "0.0 fwhm = 0.7 # Arcsec for Kolmogorov profile sky_level = 1000.0 #", "dz_fit = fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit #", "2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4,", "np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)):", "sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm, (),", "np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use the transverse aberration # zernikes", "{ 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4", "= np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9, 20e-9, 11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface,", "fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model(", "thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use the transverse aberration", "np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.1, \"rms %9.3f > 0.1\"", "<reponame>jmeyers314/danish import os import pickle import time from scipy.optimize import least_squares import numpy", "c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4,", "time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm():", "z_perturbs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] =", "= 2 for datum in data[1:niter]: thx = datum['thx'] thy = datum['thy'] z_ref", "dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms", "gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2", "\"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f)", "mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model", "guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time()", "plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0,", ") dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar + [0.7]", "= np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.02\" % rms @timer", "obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy,", "using danish model to produce a test images of rigid-body perturbed LSST transverse", "M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5,", "nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar,", "fitter run through the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\",", "0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs", "1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = {", "fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] +", "= batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms = (", "@timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data", "the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0,", "np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph))", "rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f > %9.3\" % (rms1x1,", "t0 = time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", "so flip based on # that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol =", "0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce", "2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img =", "7), (1, 8), # constant coma (1, 9), (1, 10), # constant trefoil", "dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs) guess = [0.0]*nstar + [0.0]*nstar", "sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with DOF to optimize... fitter = danish.MultiDonutModel(", "open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory =", ") for i in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\"", "cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz])", "(z_perturb - z_ref)[4:12] # NOTE: The R_inner and focal_length here don't quite match", "in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out +=", "assert rms < 0.2, \"rms %9.3f > 0.2\" % rms # mods =", "= fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3", "= 10 else: niter = 2 for datum in data[1:niter]: thx = datum['thx']", "jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms = np.arange(4, 12) z_true = (z_perturb", "= data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = [] thys =", "binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1]", "Zernikes. Model and fitter run through the same code. \"\"\" # Nominal donut", "np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def", "0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img,", "14), (1, 15), # quatrefoil (1, 16), (1, 17), (1, 18), (1, 19),", "< 2*tol, \"rms %9.3f > %9.3\" % (rms1x1, tol) # Try binning 2x2", "= np.array(z_fit) # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # )", "NOTE: The R_inner and focal_length here don't quite match what I've # seen", "+= f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit =", "danish model to produce a test image with fiducial LSST transverse Zernikes plus", "fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms <", "fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength = 750e-9 rng =", "dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce", "pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if", "max_nfev=20, verbose=2, args=(img, sky_level) ) t1 = time.time() t1x1 = t1 - t0", "z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm,", "Arcsec for Kolmogorov profile sky_level = 1000.0 # counts per pixel # Make", "gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2 = t1 -", "np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.2, \"rms %9.3f > 0.2\"", "rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0 img = fitter.model(", "t1 = time.time() t1x1 = t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "= 0.0, 0.0 fwhm = 0.7 # Arcsec for Kolmogorov profile sky_level =", "since danish uses a transverse aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx,", "np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms", "fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar", "tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1", "rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.1, \"rms %9.3f", "batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms = ( (1,", "figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in enumerate(zip(imgs, mods)):", "plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce a test", "@timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of", "= danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5,", "os import pickle import time from scipy.optimize import least_squares import numpy as np", ") binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level =", "\"rms %9.3f > 0.6\" % rms # Try binning 2x2 binned_fitter = danish.SingleDonutModel(", "= np.array(z_fit) # Optional visualization # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit,", ") ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy =", "atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms", "# We don't ship a custom fitting algorithm; just use scipy.least_squares result =", "rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model( dxs, dys,", "0.2, \"rms %9.3f > 0.2\" % rms # mods = fitter.model( # dxs_fit,", "np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth' ) if ylim is None: ylim", "a test image with fiducial LSST transverse Zernikes plus random Zernike offsets. Model", "test image of rigid-body perturbed AuxTel transverse Zernikes. Model and fitter run through", "Nominal donut mode for AuxTel is to despace M2 by 0.8 mm fiducial_telescope", "test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs", "cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr = np.sqrt(rng.uniform(0,", ") sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual']", "0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms", "rms < 0.1, \"rms %9.3f > 0.1\" % rms # mods = fitter.model(", "test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f)", "0.7]+[0.0]*8 # We don't ship a custom fitting algorithm; just use scipy.least_squares result", "pixel_scale=10e-6 ) # Toy zfitter to make test images fitter0 = danish.MultiDonutModel( factory,", "scipy.optimize import least_squares import numpy as np import batoid import danish from test_helpers", "gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 23): out =", "fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm,", "npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares( binned_fitter.chi, guess,", "fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms <", "guess aberrations are 0.0, and try to recover truth. guess = [0.0, 0.0,", "reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms = ( (1, 4), #", "z_terms = np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12] # NOTE: The R_inner", "np.random.default_rng(234) if __name__ == \"__main__\": niter = 10 else: niter = 2 for", "eps=0.2115/0.6 ) z_perturb *= wavelength z_terms = np.arange(4, 12) z_true = (z_perturb -", "kmax=10, jmax=66, eps=0.61 ) dz_terms = ( (1, 4), # defocus (2, 4),", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__ ==", "constant coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "z_fit/wavelength, z_true/wavelength) # One fit is problematic. It has a large field angle,", "ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax),", "10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys", "rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.4, \"rms %9.3f", "# plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit is problematic. It has a", "Model and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb'", "nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i, (thx,", "a transverse aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20,", "imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4), # defocus (2, 4), (3, 4),", "# ) @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as", "wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb = batoid.zernikeTA(", "= fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0,", "= [sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "# imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using", "z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys =", "batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy", "phase screen atmosphere + batoid to produce test image of AOS DOF perturbed", "dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx,", "naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20,", "16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732,", "fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true =", "# dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) #", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms,", "test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test images of rigid-body perturbed", "@timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere + batoid to produce", "= fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now guess aberrations", "[5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual", "mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth')", "{(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # mod", "def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce test images with fiducial", "danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar)", "gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 12): out =", "z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit is problematic.", "z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r',", "'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit,", "wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope, thx, thy,", "niter = 10 else: niter = 1 for _ in range(niter): M2_dx, M2_dy", "dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms", "AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def", "\"M2\", [0, 0, 0.0008] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__", "in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx,", "gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in enumerate(zip(imgs, mods)): ax0 =", "pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__ == \"__main__\": niter = 10 else:", "'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii =", "rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f > %9.3\"", "cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy =", "fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now guess aberrations are", "Roundtrip using danish model to produce a test image with fiducial LSST transverse", "z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f >", "thys=thys ) nstar = len(thxs) guess = [0.0]*nstar + [0.0]*nstar + [0.7] +", "thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 result = least_squares(", "dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength,", "spherical (1, 12), (1, 13), # second astigmatism (1, 14), (1, 15), #", "rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip", "second astigmatism (1, 14), (1, 15), # quatrefoil (1, 16), (1, 17), (1,", ") binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__", "= data[0]['dz_actual'] thxs = [] thys = [] z_refs = [] z_actuals =", ") ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0,", "fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx,", "verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2 = t1 - t0 dx_fit,", "dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8),", "(1, 13), # second astigmatism (1, 14), (1, 15) # quatrefoil ) dz_true", "4*sky_level) ) t1 = time.time() t2x2 = t1 - t0 dx_fit, dy_fit, fwhm_fit,", ".withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] =", "just use scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", ") fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs =", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength =", "# Make a test image using true aberrations img = fitter.model( dx, dy,", "= batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs", "c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms)))", "= danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = 0.0, 0.0", "fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms", "print(f\"rms = {rms:9.3f} waves\") assert rms < 0.05, \"rms %9.3f > 0.05\" %", "size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) )", "12), (1, 13), # second astigmatism (1, 14), (1, 15) # quatrefoil )", "jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth' )", "10 else: niter = 2 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4,", "0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344) nstar = 10 if __name__", "wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms = ( (1, 4), # defocus", "np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose(", "= fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with", "telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng", "np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f > 0.6\"", "f: data = pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\"", "ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods,", "optics. Model and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"),", "[0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3,", "= np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12] # NOTE: The R_inner and", "[] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms =", "z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = 0.0, 0.0 fwhm = 0.7", "\"\"\"Roundtrip using danish model to produce a test images of rigid-body perturbed LSST", "thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph))", "= np.random.default_rng(2344) nstar = 10 if __name__ == \"__main__\": niter = 10 else:", "cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23)", "result.x z_fit = np.array(z_fit) # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit", "z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5", "2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx,", "telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar =", "np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms = ( (1, 4), #", "# defocus (2, 4), (3, 4), # field tilt (2, 5), (3, 5),", "gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1 = time.time() t1x1 = t1 -", "niter = 10 else: niter = 2 for _ in range(niter): # Randomly", "data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "t1x1 = t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23):", "M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([", "= plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1", "jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit", "factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm", "second astigmatism (1, 14), (1, 15) # quatrefoil ) dz_true = np.empty(len(dz_terms)) for", "# imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with open(", "= t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit)", "< 0.05, \"rms %9.3f > 0.05\" % rms # dxs_fit, dys_fit, fwhm_fit, dz_fit", "wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66,", "[1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes", "- t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod", "danish model to produce a test image of rigid-body perturbed LSST transverse Zernikes.", "fitter run through the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic(", "fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit,", "0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(124) if __name__ == \"__main__\": niter", "*= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 )", "dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2)", "batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng", "= np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)),", "Roundtrip using danish model to produce test images with fiducial LSST transverse Zernikes", "def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce a test image with", "focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__ == \"__main__\": niter = 10", "open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory =", "fitting algorithm; just use scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3,", "astigmatism (1, 7), (1, 8) # constant coma ) dz_true = rng.uniform(-0.3, 0.3,", ":]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r',", "dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with DOF to optimize...", "binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3,", "donut mode for AuxTel is to despace M2 by 0.8 mm fiducial_telescope =", "= telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344) nstar =", "= np.array(z_fit) # mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # )", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms", "fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # mod = fitter.model( # dx_fit,", "= batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref", "dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod = binned_fitter.model(", "f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "i, (img, mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i,", "visualization # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) #", "fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k',", "and fitter run through the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope =", ") t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit", "(1, 22) ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] =", "jmax=66, eps=0.61 ) z_ref *= wavelength z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1,", "rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0,", "future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter", "= fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(234)", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_terms", "\"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0,", "sky_level) ) for i in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out +=", "zfitter to make test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs,", "# ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test", "= (z_perturb - z_ref)[4:12] # NOTE: The R_inner and focal_length here don't quite", "M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5,", "9), (1, 10), # constant trefoil (1, 11), # constant spherical (1, 12),", "result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels)", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms =", "aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol,", "for future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 )", "data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = []", "aberrations img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now", "fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f}", ") z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\"", "import timer directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner':", "2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085,", "= 1000.0 # counts per pixel # Make a test image using true", "dz_true, dz_terms): import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs =", "dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod = binned_fitter.model( #", "data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory =", "%9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2", "np.random.default_rng(2344) nstar = 10 if __name__ == \"__main__\": niter = 10 else: niter", ") binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac,", "2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2)", "rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use", "for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy,", "# constant trefoil (1, 11), # constant spherical (1, 12), (1, 13), #", "naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs *= wavelength dz_ref =", "ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\"", "batoid to produce test image of AOS DOF perturbed optics. Model and fitter", ") dx, dy = 0.0, 0.0 fwhm = 0.7 sky_level = 1000.0 img", ") if __name__ == \"__main__\": niter = 10 else: niter = 2 for", "# second astigmatism (1, 14), (1, 15) # quatrefoil ) dz_true = np.empty(len(dz_terms))", "# plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm():", "rms # dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods = fitter.model( #", "dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_terms =", "z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img = img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result =", "reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms = np.arange(4, 12) z_true =", "z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f >", "= time.time() result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "LSST transverse Zernikes. Model and fitter run through the same code. \"\"\" fiducial_telescope", "0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345,", "dys = rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes", "@timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of", "wavelength z_terms = np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12] # NOTE: The", "random Zernike offsets. Model and fitter run through the same code. \"\"\" telescope", "elsewhere. Possible location for future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion,", ") fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy =", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\": niter = 10 else:", "z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms =", "{t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip", "thxs = [] thys = [] z_refs = [] z_actuals = [] imgs", "fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0 img = fitter.model( dx, dy, fwhm,", "z_true = (z_perturb - z_ref)[4:12] # NOTE: The R_inner and focal_length here don't", "= 2 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz", "using danish model to produce a test image of rigid-body perturbed LSST transverse", "M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz =", "args=(img, sky_level) ) t1 = time.time() t1x1 = t1 - t0 z_true =", "fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 <", "0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2)", "z_ref *= wavelength z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory", "\"__main__\": niter = 10 else: niter = 2 for _ in range(niter): #", "0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :])", "dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a", ") dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] -", "(1, 11), # constant spherical (1, 12), (1, 13), # second astigmatism (1,", "produce test image of AOS DOF perturbed optics. Model and fitter run independent", "print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere + batoid to", "mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results( #", "dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs,", ") .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0,", "test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce a test image with fiducial", "of rigid-body perturbed AuxTel transverse Zernikes. Model and fitter run through the same", "for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5,", "4*sky_level) ) t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit,", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms", ") for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\"", "{rms:9.3f} waves\") assert rms < 0.4, \"rms %9.3f > 0.4\" % rms #", "ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot(", "2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use the", "linear astigmatism (1, 7), (1, 8) # constant coma ) dz_true = rng.uniform(-0.3,", "(1, 9), (1, 10), # constant trefoil (1, 11), # constant spherical (1,", ") # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0,", "+ batoid to produce test image of AOS DOF perturbed optics. Model and", "0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish", "= np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess", "= rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes.", ") ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer", "dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19 result =", "DOF to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys )", "batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10 thr = np.sqrt(rng.uniform(0,", "cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy,", "pickle import time from scipy.optimize import least_squares import numpy as np import batoid", "field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5,", "coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True,", "z_refs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] =", "\"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength # The", "= data[0]['wavelength'] fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit,", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to make", "= telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface(", "np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2))", "\"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx,", "mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod,", "= ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) #", "= danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs) guess", "args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2 = t1 - t0 dx_fit, dy_fit,", "sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d}", "niter = 10 else: niter = 1 for _ in range(niter): thr =", "constant coma (1, 9), (1, 10), # constant trefoil (1, 11), # constant", "range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\"", "binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 =", "= fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results( # imgs,", "z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy = 0.0, 0.0 fwhm = 0.7", "z_ref)[4:12] # NOTE: The R_inner and focal_length here don't quite match what I've", "custom fitting algorithm; just use scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3,", "ylim is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4,", "naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms = np.arange(4, 23) z_true", "dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms", "least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for", "transverse aberration # zernikes since danish uses a transverse aberration ray-hit model. z_ref", "= f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit,", "print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # Optional visualization", "z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth' ) if", "transverse Zernikes plus random Zernike offsets. Model and fitter run through the same", "focal_length here don't quite match what I've # seen elsewhere. Possible location for", "= 10 else: niter = 2 for _ in range(niter): M2_dx, M2_dy =", "np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f", "niter = 1 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph", "in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out +=", "- mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true,", "0.1, \"rms %9.3f > 0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim", "print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # mod =", "a test images of rigid-body perturbed LSST transverse Zernikes. Model and fitter run", "batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *=", "= danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy = 0.0,", "\"\"\"Roundtrip using danish model to produce a test image of rigid-body + M1-surface-Zernike", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms,", "(z_fit-z_true), c='r', label='fit - truth' ) if ylim is None: ylim = -0.6,", "quatrefoil (1, 16), (1, 17), (1, 18), (1, 19), (1, 20), (1, 21),", "z_terms=z_terms, thx=thx, thy=thy ) dx, dy = 0.0, 0.0 fwhm = 0.7 sky_level", "produce a test images of rigid-body perturbed LSST transverse Zernikes. Model and fitter", "3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx,", "z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 )", ".withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar))", ".withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr", "'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 }", "ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual", "3) for i, (img, mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1", "'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit':", "c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit -", "[5e6]*nstar imgs = fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess =", "\"rms %9.3f > 0.1\" % rms # mods = fitter.model( # dxs_fit, dys_fit,", "%9.3f > 0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to", "= time.time() t2x2 = t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x", "import os import pickle import time from scipy.optimize import least_squares import numpy as", "# ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true,", "label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\")", "Now guess aberrations are 0.0, and try to recover truth. guess = [0.0,", "rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms <", "term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength,", "based on # that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7 else:", "astigmatism (1, 7), (1, 8) # constant coma ) dz_true = np.empty(len(dz_terms)) for", "astigmatism (1, 14), (1, 15), # quatrefoil (1, 16), (1, 17), (1, 18),", "plus random double Zernike offsets. Model and fitter run through the same code.", "= least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) )", "improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter =", "15) # quatrefoil ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i]", "linear astigmatism (1, 7), (1, 8), # constant coma (1, 9), (1, 10),", "defocus (2, 4), (3, 4), # field tilt (2, 5), (3, 5), (2,", "thys=thys ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result =", "= rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter.model( dxs,", "z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 t0 =", "time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) #", "atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f > %9.3\" %", "timer directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487,", "size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter =", "to produce a test image of rigid-body perturbed AuxTel transverse Zernikes. Model and", "thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 t0 = time.time() result", "= 1 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz", "{z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\":", "z_fit = np.array(z_fit) # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit #", "rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1,", "np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope,", "for datum in data[1:niter]: thx = datum['thx'] thy = datum['thy'] z_ref = datum['z_ref']", "jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import matplotlib.pyplot as", "# ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy,", "np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.4, \"rms %9.3f > 0.4\"", "M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10 thr =", "% rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # )", "dy = rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5) sky_level = 1000.0 img", "alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy", "gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f}", "(1, 7), (1, 8) # constant coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength", "else: niter = 2 for datum in data[1:niter]: thx = datum['thx'] thy =", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2 = t1", "AOS DOF perturbed optics. Model and fitter run independent code. \"\"\" with open(", "rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2)", "# constant coma ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i]", "def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere + batoid to produce test", "> 1.7: tol = 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2)", "2*tol, \"rms %9.3f > %9.3\" % (rms1x1, tol) # Try binning 2x2 binned_fitter", ") rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.05, \"rms", "ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope,", "Kolmogorov atmosphere + batoid to produce test image of AOS DOF perturbed optics.", "for i in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\"", "print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer", "8), # constant coma (1, 9), (1, 10), # constant trefoil (1, 11),", ") guess = [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3,", "eps=0.61 ) z_ref *= wavelength z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1,", "from test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer':", "% (rms1x1, tol) # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms,", "factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter", "niter = 2 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2)", "[] z_actuals = [] imgs = [] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy'])", "0.1, \"rms %9.3f > 0.1\" % rms # mods = fitter.model( # dxs_fit,", "dx, dy = 0.0, 0.0 fwhm = 0.7 sky_level = 1000.0 img =", "c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth' ) if ylim", "fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng =", "img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0,", "sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb", "ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit,", "12) z_true = (z_perturb - z_ref)[4:12] # NOTE: The R_inner and focal_length here", "img = datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength,", "= batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb", "0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter", "= [5e6]*nstar imgs = fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess", "# dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit,", "rng = np.random.default_rng(2344) nstar = 10 if __name__ == \"__main__\": niter = 10", "[0.0, 0.0, 0.7] + [0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3,", "> 0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce", "np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for i, (thx, thy)", "image with fiducial LSST transverse Zernikes plus random Zernike offsets. Model and fitter", "thy = datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1]", "time.time() t1x1 = t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4,", "rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol,", ") # Random point inside 0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2))", "np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref =", "1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) -", "dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit,", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to make test images fitter0 =", "tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 =", "import least_squares import numpy as np import batoid import danish from test_helpers import", "+= f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit)", "fluxes=fluxes ) # Actual fitter with DOF to optimize... fitter = danish.MultiDonutModel( factory,", "wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs *= wavelength", "'M3_inner': 1.1919725733251365, 'L1_entrance': 7.692939426566589, 'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit':", "np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit,", "mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms", "dz_fit # ) # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # )", "plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip", "dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms =", "os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) sky_level = data[0]['sky_level']", "z_fit = np.array(z_fit) # mod = binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit #", "fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs)", "fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1 =", "[] z_refs = [] z_actuals = [] imgs = [] for datum in", "truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show()", "t2x2 = t1 - t0 dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit =", "wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength # The zernikes", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i in", "236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = {", "(3, 6), # linear astigmatism (1, 7), (1, 8) # constant coma )", "np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms", "figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0,", "{rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere + batoid", "*= wavelength # The zernikes of the perturbed telescope. I.e., the \"truth\". z_perturb", "enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66,", "assert rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation():", "7), (1, 8) # constant coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory", "dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms =", "(1, 15), # quatrefoil (1, 16), (1, 17), (1, 18), (1, 19), (1,", "# plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2)", "to make test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys", "i in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\" {z_true[i-4]/wavelength:9.3f}\" out", "= danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar +", "# Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89", "fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as", "datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel( factory,", "has a large field angle, so flip based on # that. if np.rad2deg(np.hypot(thx,", "z_true = (z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31,", "30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727,", "sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1", "np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit,", "fwhm_fit, dz_fit # ) # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms #", "% rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid to", "np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\")", "\"rms %9.3f > 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish", "batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9,", "= np.random.default_rng(1234) if __name__ == \"__main__\": niter = 10 else: niter = 1", "thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120,", "scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img,", "0.2\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit #", "c='b', label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit", "assert rms < 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_z_perturbation():", "os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory(", "= rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii,", "using GalSim phase screen atmosphere + batoid to produce test image of AOS", "# plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength)", "danish model to produce a test images of rigid-body perturbed LSST transverse Zernikes.", "sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using", "by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008]", "assert rms < 0.05, \"rms %9.3f > 0.05\" % rms # dxs_fit, dys_fit,", "28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959,", "(dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\")", "R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__ == \"__main__\":", "jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61", "= pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level", ") # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms", "0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit, z_true,", "for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength", "def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test images of rigid-body", "3) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2])", "# second astigmatism (1, 14), (1, 15), # quatrefoil (1, 16), (1, 17),", "[] imgs = [] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1,", "= np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.4, \"rms %9.3f >", "of the perturbed telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy,", "constant spherical (1, 12), (1, 13), # second astigmatism (1, 14), (1, 15),", "eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 )", "= rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer,", "= telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar", "z_actuals = [] imgs = [] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref'])", "thx=thx, thy=thy, npix=255 ) dx, dy = 0.0, 0.0 fwhm = 0.7 #", ") rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.2, \"rms", "reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength # The zernikes of the perturbed", "> %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit", ") z_ref *= wavelength z_terms = np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength", "sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod =", "rng.uniform(-3e-5, 3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\",", "fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength", "{rms:9.3f} waves\") assert rms < 0.6, \"rms %9.3f > 0.6\" % rms @timer", ") wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter =", "t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out =", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] dz_ref = data[0]['dz_ref']", "least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1", "[cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph", "> 0.1\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit", "== \"__main__\": niter = 10 else: niter = 2 for datum in data[1:niter]:", ") # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit is problematic. It has", "[0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) sky_levels = [sky_level]*nstar result = least_squares(", "dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term])", "offsets. Model and fitter run through the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\")", "dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5,", ") z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120,", "M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx, M2_thy = rng.uniform(-3e-5, 3e-5, size=2) telescope = (", "# ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2)", "dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with DOF to", "8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136", "in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief',", "nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref *= wavelength # The zernikes of", "'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit':", "rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.2, \"rms %9.3f", "} LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner':", "\"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) wavelength = data[0]['wavelength'] factory", "atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms =", "dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit, dys_fit,", "telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\",", ") guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result = least_squares(", "z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi,", "np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength,", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_terms =", "wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy", "as f: data = pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "quatrefoil ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term]", "rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim phase screen atmosphere +", "trefoil (1, 11), # constant spherical (1, 12), (1, 13), # second astigmatism", "produce a test image of rigid-body perturbed LSST transverse Zernikes. Model and fitter", "0.0, 0.7]+[0.0]*8 # We don't ship a custom fitting algorithm; just use scipy.least_squares", "mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2)", ") dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 )", "the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11,", "% (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f}", "dy = 0.0, 0.0 fwhm = 0.7 # Arcsec for Kolmogorov profile sky_level", "truth' ) if ylim is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\")", "don't ship a custom fitting algorithm; just use scipy.least_squares result = least_squares( fitter.chi,", "# ) # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer", "'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img, mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import", "gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4,", "Actual fitter with DOF to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8),", "%9.3f > 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model", "- truth' ) ax3.set_ylim(-0.6, 0.6) ax3.set_xlabel(\"Double Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend()", "rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.02\"", "= 10 else: niter = 2 for _ in range(niter): thr = np.sqrt(rng.uniform(0,", "(1, 12), (1, 13), # second astigmatism (1, 14), (1, 15) # quatrefoil", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6", "3e-5, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy)", "z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 )", "\"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[12:23] = rng.uniform(-20e-9,", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs,", "wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike( telescope, np.deg2rad(1.8), wavelength, rings=10,", ") # Actual fitter with DOF to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs,", "is problematic. It has a large field angle, so flip based on #", "and try to recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 # We don't", "as np import batoid import danish from test_helpers import timer directory = os.path.dirname(__file__)", "< 0.6, \"rms %9.3f > 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using", "assert rms < 0.4, \"rms %9.3f > 0.4\" % rms # mods =", "if ylim is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\")", "def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test image of rigid-body", "cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0,", "fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit", "dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true,", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength']", "'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 }", "\"\"\"Roundtrip using GalSim phase screen atmosphere + batoid to produce test image of", "rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0,", "0.6, \"rms %9.3f > 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish", "== \"__main__\": niter = 10 else: niter = 2 for _ in range(niter):", "> 0.1\" % rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce", "DOF perturbed optics. Model and fitter run independent code. \"\"\" with open( os.path.join(directory,", "guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit,", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to", "rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image", "3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734", "Toy zfitter to make test images fitter0 = danish.MultiDonutModel( factory, z_refs=z_perturbs, dz_terms=(), field_radius=np.deg2rad(1.8),", "thys = [] z_refs = [] z_actuals = [] imgs = [] for", "*z_fit = result.x z_fit = np.array(z_fit) # Optional visualization # mod = fitter.model(", "verbose=2, args=(img, sky_level) ) for i in range(4, 12): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\"", "same code. \"\"\" # Nominal donut mode for AuxTel is to despace M2", "radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy =", "quite match what I've # seen elsewhere. Possible location for future improvement. factory", ") dz_terms = ( (1, 4), # defocus (2, 4), (3, 4), #", ") # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def", "= np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true", "z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar + [0.0]*nstar + [0.7]", ") z_refs *= wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength,", "= fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod))", "test images with fiducial LSST transverse Zernikes plus random double Zernike offsets. Model", "(1, 20), (1, 21), (1, 22) ) dz_true = np.empty(len(dz_terms)) for i, term", "# Nominal donut mode for AuxTel is to despace M2 by 0.8 mm", "thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use the transverse", "time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms:", "print(f\"1x1 rms: {rms1x1}\") print(f\"2x2 rms: {rms2x2}\") print(\"\\n\"*4) @timer def test_fitter_LSST_atm(): \"\"\"Roundtrip using GalSim", "to recover truth. guess = [0.0, 0.0, 0.7]+[0.0]*8 # We don't ship a", "(Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms): import", "'L1_exit': 8.103064894823262, 'L2_entrance': 10.746925431763076, 'L2_exit': 11.548732622162085, 'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit':", "> 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to", "def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test images of rigid-body", "> 0.4\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit", "batoid.Optic.fromYaml(\"AuxTel.yaml\") fiducial_telescope = fiducial_telescope.withLocallyShiftedOptic( \"M2\", [0, 0, 0.0008] ) wavelength = 750e-9 rng", "z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2))", "= 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2))", "7), (1, 8) # constant coma ) dz_true = np.empty(len(dz_terms)) for i, term", "thx = datum['thx'] thy = datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual'] img", "import batoid import danish from test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii =", "fit is problematic. It has a large field angle, so flip based on", "M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope =", "10 else: niter = 2 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2))", "dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # mod = fitter.model(", ") dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm =", "model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6", "[0, 0, 0.0008] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ ==", "R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\": niter =", "\"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr", "6), # linear astigmatism (1, 7), (1, 8), # constant coma (1, 9),", "rigid-body perturbed AuxTel transverse Zernikes. Model and fitter run through the same code.", "# constant coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory = danish.DonutFactory( R_outer=4.18,", "= rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5,", "args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit,", "sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 )", "np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)):", "= np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) # Determine reference \"design\" zernikes. Use the transverse aberration #", "0.1, \"rms %9.3f > 0.1\" % rms @timer def test_dz_fitter_LSST_fiducial(): \"\"\" Roundtrip using", "2 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi)", "[1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model( dxs, dys, fwhm, (), sky_levels=sky_levels, fluxes=fluxes", "ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit, dz_true, dz_terms):", "batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234)", "verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0,", "fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(234) if", "= time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "10 else: niter = 1 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4,", "obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__ == \"__main__\": niter =", ") dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i] = (dz_perturb[term] -", "67)) z_perturbs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i]", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x)", "= pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory =", "thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 result = least_squares( fitter.chi,", "(1, 16), (1, 17), (1, 18), (1, 19), (1, 20), (1, 21), (1,", "don't quite match what I've # seen elsewhere. Possible location for future improvement.", "wavelength # The zernikes of the perturbed telescope. I.e., the \"truth\". z_perturb =", "label='fit') ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit -", "= batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i]", "np.zeros(23) M1_a[9:16] = rng.uniform(-20e-9, 20e-9, 7) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike(", "imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_atm(): with open( os.path.join(directory,", "(z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out += f\"", "the same code. \"\"\" # Nominal donut mode for AuxTel is to despace", "= batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_ref", "> 0.05\" % rms # dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods", "seen elsewhere. Possible location for future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii,", "dz_terms): import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3,", "Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 )", "= np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for i,", "niter = 10 else: niter = 2 for _ in range(niter): M2_dx, M2_dy", "dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength,", "= telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__", "print(f\"rms = {rms:9.3f} waves\") assert rms < 0.1, \"rms %9.3f > 0.1\" %", "(rms1x1, tol) # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx,", "z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 )", "> %9.3\" % (rms1x1, tol) # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory,", "= { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner': -2.7000030360993734 } def plot_result(img,", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory,", "= np.arange(4, 23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "# imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__ == \"__main__\": test_fitter_LSST_fiducial()", "factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = 0.0, 0.0 fwhm =", "\"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9", "max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit,", "factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy = 0.0, 0.0 fwhm", ") .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1']", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) t1 = time.time() t1x1 =", "M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) )", "waves\") assert rms < 0.4, \"rms %9.3f > 0.4\" % rms # mods", "imgs = [] for datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1])", "wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms = (", "guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength", "print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms: {rms1x1}\")", "0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "fwhm = data[0]['fwhm'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 )", "focal_length=10.31, pixel_scale=10e-6 ) # Toy zfitter to make test images fitter0 = danish.MultiDonutModel(", "print(f\"rms = {rms:9.3f} waves\") assert rms < 0.4, \"rms %9.3f > 0.4\" %", "through the same code. \"\"\" # Nominal donut mode for AuxTel is to", "= -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show()", "= datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel(", "enumerate(dz_terms): dz_true[i] = (dz_perturb[term] - dz_ref[term]) dz_true *= wavelength factory = danish.DonutFactory( R_outer=4.18,", "z_perturb *= wavelength z_terms = np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12] #", "datum['thx'] thy = datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1,", "- t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d}", "batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph =", "12), (1, 13), # second astigmatism (1, 14), (1, 15), # quatrefoil (1,", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs *=", "fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(124) if", "# mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img,", "rms # Try binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy,", "reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_terms = np.arange(4, 23) z_true =", "'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner':", "dx, dy = 0.0, 0.0 fwhm = 0.7 # Arcsec for Kolmogorov profile", "telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr =", "> 0.6\" % rms @timer def test_fitter_AuxTel_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce", ") @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test images", "z_terms = np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18,", "= time.time() t1x1 = t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in", "using true aberrations img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 )", "plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2", "using danish model to produce test images with fiducial LSST transverse Zernikes plus", "4), # field tilt (2, 5), (3, 5), (2, 6), (3, 6), #", "profile sky_level = 1000.0 # counts per pixel # Make a test image", "14), (1, 15) # quatrefoil ) dz_true = np.empty(len(dz_terms)) for i, term in", "{rms:9.3f} waves\") assert rms < 0.2, \"rms %9.3f > 0.2\" % rms #", "label='fit') ax3.plot(dz_true, c='k', label='truth') ax3.plot( (dz_fit-dz_true), c='r', label='fit - truth' ) ax3.set_ylim(-0.6, 0.6)", ") sky_level = data[0]['sky_level'] if __name__ == \"__main__\": niter = 10 else: niter", "\"rms %9.3f > %9.3\" % (rms2x2, tol) print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\")", "dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert", "use scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0]) ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i,", "\"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model", "= img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3,", "(1, 14), (1, 15), # quatrefoil (1, 16), (1, 17), (1, 18), (1,", "result.x z_fit = np.array(z_fit) # Optional visualization # mod = fitter.model( # dx_fit,", "0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344) nstar = 10 if __name__ ==", "%9.3f > 0.4\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit,", "pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs", "binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level)", "per pixel # Make a test image using true aberrations img = fitter.model(", ") dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose(dxs, dxs_fit, rtol=0, atol=0.2) np.testing.assert_allclose(dys, dys_fit,", "model to produce a test image of rigid-body + M1-surface-Zernike perturbed LSST transverse", "# counts per pixel # Make a test image using true aberrations img", "= np.random.default_rng(124) if __name__ == \"__main__\": niter = 10 else: niter = 1", "ax1 = fig.add_subplot(gs[i, 1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod))", "as f: data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm =", "@timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid to produce test", "+ M1-surface-Zernike perturbed LSST transverse Zernikes. Model and fitter run through the same", "thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm = rng.uniform(0.5, 1.5)", "wavelength = 750e-9 rng = np.random.default_rng(124) if __name__ == \"__main__\": niter = 10", "jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() t2x2", "dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # mod = fitter.model( #", "guess = [0.0, 0.0, 0.7] + [0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac,", "[0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", "% rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test", "]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy =", "np.testing.assert_allclose(dys, dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1", "wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturb *= wavelength z_terms = np.arange(4,", "__name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm() test_fitter_AuxTel_rigid_perturbation() test_dz_fitter_LSST_fiducial() test_dz_fitter_LSST_rigid_perturbation() test_dz_fitter_LSST_z_perturbation() test_dz_fitter_LSST_kolm()", "least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) z_true", "(), sky_levels=sky_levels, fluxes=fluxes ) # Actual fitter with DOF to optimize... fitter =", "= batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015] ) wavelength = 750e-9", "M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz = rng.uniform(-3e-5, 3e-5) M2_thx,", "in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1, 4),", "{t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod", "plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit,", "z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter =", "2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength,", "atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength)", "print(\"\\n\"*4) print(f\"1x1 fit time: {t1x1:.3f} sec\") print(f\"2x2 fit time: {t2x2:.3f} sec\") print(f\"1x1 rms:", "range(niter): # Randomly perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz", "= batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10, jmax=66, eps=0.61 ) dz_perturb = batoid.analysis.doubleZernike(", "+ [0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2,", "nstar = 10 if __name__ == \"__main__\": niter = 10 else: niter =", "max_nfev=20, verbose=2, args=(imgs, sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength,", "= [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce", "\"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph", "using danish model to produce a test image of rigid-body perturbed AuxTel transverse", "= binned_fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength,", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs,", ") ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy", "imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish", "23) z_true = rng.uniform(-0.1, 0.1, size=19)*wavelength factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "for _ in range(niter): # Randomly perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4,", "R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph", "thx=thx, thy=thy ) dx, dy = 0.0, 0.0 fwhm = 0.7 sky_level =", "with DOF to optimize... fitter = danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys", "os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner':", "batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) thr = np.sqrt(rng.uniform(0, 1.8**2))", "fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod) in enumerate(zip(imgs, mods)): ax0 = fig.add_subplot(gs[i, 0])", "0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\": niter", "= t1 - t0 z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out", "batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr =", "GalSim Kolmogorov atmosphere + batoid to produce test image of AOS DOF perturbed", "[0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ ==", "pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx,", "Model and fitter run through the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope", "# Random point inside 0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph", "rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f > %9.3\" % (rms2x2,", "a custom fitting algorithm; just use scipy.least_squares result = least_squares( fitter.chi, guess, jac=fitter.jac,", "M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ]) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2,", "53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333,", "17), (1, 18), (1, 19), (1, 20), (1, 21), (1, 22) ) dz_true", "else: niter = 2 for _ in range(niter): thr = np.sqrt(rng.uniform(0, 1.8**2)) ph", ") if ylim is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual", "data = pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "We don't ship a custom fitting algorithm; just use scipy.least_squares result = least_squares(", "perturbed telescope. I.e., the \"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20,", ") # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0,", ") # plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit,", "for Kolmogorov profile sky_level = 1000.0 # counts per pixel # Make a", "dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb'", "= { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216, 'M3_inner': 1.1919725733251365, 'L1_entrance':", "telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(234) if", "test image of rigid-body + M1-surface-Zernike perturbed LSST transverse Zernikes. Model and fitter", "# plot_result(img, mod, z_fit/wavelength, z_true/wavelength, ylim=(-0.2, 0.2)) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=1e-2) np.testing.assert_allclose(dy_fit, dy,", "\"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18,", "= 10 if __name__ == \"__main__\": niter = 10 else: niter = 1", "location for future improvement. factory = danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6", "= 10 else: niter = 2 for _ in range(niter): # Randomly perturb", "= 0.7 # Arcsec for Kolmogorov profile sky_level = 1000.0 # counts per", "ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k', label='truth')", "t0 = time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", "# imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using", "dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true,", "atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms", "mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod,", "mod, z_fit, z_true, ylim=None): jmax = len(z_fit)+4 import matplotlib.pyplot as plt fig =", "2 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz =", "dz_ref = data[0]['dz_ref'] dz_actual = data[0]['dz_actual'] thxs = [] thys = [] z_refs", "'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138, 'M3_inner': 53.2113063872138, 'L1_entrance': 131.69949884635324, 'L1_exit': 137.51151184228345, 'L2_entrance':", "= fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms =", "field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms)", "mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation()", "matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0", "\"\"\"Roundtrip using danish model to produce a test image of rigid-body perturbed LSST", "data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm'] factory", "angle, so flip based on # that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol", "# Randomly perturb M2 alignment M2_dx, M2_dy = rng.uniform(-3e-4, 3e-4, size=2) M2_dz =", "wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6 ) z_perturb *= wavelength z_terms = np.arange(4,", "same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") fiducial_telescope = fiducial_telescope.withGloballyShiftedOptic( \"Detector\", [0, 0, 0.0015]", "eps=0.61 ) z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20,", "ax3.plot(np.arange(4, jmax), z_true, c='k', label='truth') ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth'", "dz_actual = data[0]['dz_actual'] thxs = [] thys = [] z_refs = [] z_actuals", "flux=5e6 ) # Now guess aberrations are 0.0, and try to recover truth.", "danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ == \"__main__\": niter", "= np.arange(4, 23) z_true = (z_perturb - z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "= fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 =", "= batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref", "z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out", "rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms =", "plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One fit is problematic. It has a large", "mode for AuxTel is to despace M2 by 0.8 mm fiducial_telescope = batoid.Optic.fromYaml(\"AuxTel.yaml\")", ") as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion,", "= rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67))", "sky_levels) ) dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2", "and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' )", "atol=tol*wavelength) rms1x1 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms1x1 < 2*tol, \"rms %9.3f > %9.3\" %", "sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result", ") ]) ) nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph =", "'L1_exit': 137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit':", "rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms <", "thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms =", "z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert", "telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344) nstar = 10", "> 0.2\" % rms # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit", "19), (1, 20), (1, 21), (1, 22) ) dz_true = np.empty(len(dz_terms)) for i,", "rng = np.random.default_rng(1234) if __name__ == \"__main__\": niter = 10 else: niter =", "rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels", "directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer':", "image of rigid-body perturbed AuxTel transverse Zernikes. Model and fitter run through the", "dz_terms = ( (1, 4), # defocus (2, 4), (3, 4), # field", "= rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes = [5e6]*nstar imgs = fitter0.model( dxs,", "datum in data[1:]: thxs.append(datum['thx']) thys.append(datum['thy']) z_refs.append(datum['z_ref']) z_actuals.append(datum['z_actual']) imgs.append(datum['arr'][::-1, ::-1]) dz_terms = ( (1,", "= rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx,", "'Filter_entrance': 28.06952057721957, 'Filter_exit': 30.895257933242576, 'L3_entrance': 54.5631834759912, 'L3_exit': 114.76715786850136 } LSST_obsc_motion = { 'M1_inner':", "_ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5)", "@timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test images of", "atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.6,", "= fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 =", "= fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength,", "mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\",", "rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2) cam_dx, cam_dy = rng.uniform(-2e-3, 2e-3,", "produce a test image with fiducial LSST transverse Zernikes plus random Zernike offsets.", "rng.uniform(-2e-4, 2e-4, size=2) telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\",", "perturbed LSST transverse Zernikes. Model and fitter run through the same code. \"\"\"", "fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k') ax3.plot(np.arange(4, jmax), z_fit, c='b',", "\"rms %9.3f > 0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using GalSim Kolmogorov", "< 0.1, \"rms %9.3f > 0.1\" % rms @timer def test_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using", ") @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip using danish model to produce a test images", "index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using", "naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_perturb = batoid.zernikeTA( telescope, thx,", "= (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys", "thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120,", "dys_fit, rtol=0, atol=0.2) np.testing.assert_allclose(fwhm, fwhm_fit, rtol=0, atol=0.05) np.testing.assert_allclose( dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.1 )", "factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys", "args=(img, sky_level) ) z_true = (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out =", "label='fit - truth' ) if ylim is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim)", "21), (1, 22) ) dz_true = np.empty(len(dz_terms)) for i, term in enumerate(dz_terms): dz_true[i]", "f: data = pickle.load(f) sky_level = data[0]['sky_level'] wavelength = data[0]['wavelength'] fwhm = data[0]['fwhm']", "flip based on # that. if np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7", "dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm,", "\"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498,", "= rng.uniform(-2e-3, 2e-3, size=2) cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4,", "rms @timer def test_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish model to produce a test image", "114.76715786850136 } LSST_obsc_motion = { 'M1_inner': 0.1517605552388959, 'M2_outer': 16.818667026561727, 'M2_inner': 16.818667026561727, 'M3_outer': 53.2113063872138,", "(1, 8) # constant coma ) dz_true = rng.uniform(-0.3, 0.3, size=len(dz_terms))*wavelength factory =", "ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod))", "open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) sky_level =", "cam_dz = rng.uniform(-2e-5, 2e-5) cam_thx, cam_thy = rng.uniform(-2e-4, 2e-4, size=2) telescope = (", "16), (1, 17), (1, 18), (1, 19), (1, 20), (1, 21), (1, 22)", "= [] z_actuals = [] imgs = [] for datum in data[1:]: thxs.append(datum['thx'])", "np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f", "linear astigmatism (1, 7), (1, 8) # constant coma ) dz_true = np.empty(len(dz_terms))", ".withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2))", "transverse aberration ray-hit model. z_ref = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120,", "plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_z_perturbation(): \"\"\"Roundtrip", "rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs = np.empty((nstar, 67)) for", "= np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.05, \"rms %9.3f >", "0, 0.0008] ) wavelength = 750e-9 rng = np.random.default_rng(234) if __name__ == \"__main__\":", "ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 12):", "img[:-1,:-1].reshape(90,2,90,2).mean(-1).mean(1)[:-1,:-1] t0 = time.time() binned_result = least_squares( binned_fitter.chi, guess, jac=binned_fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2))", "i, term in enumerate(dz_terms): dz_true[i] = (dz_actual[term] - dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory,", "= rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5)", "flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac,", "rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy = rng.uniform(-2e-5, 2e-5, size=2)", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2 fit time:", "rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms <", "\"truth\". z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=11, eps=0.2115/0.6", "dxs_fit, dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength,", "# ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 )", "danish from test_helpers import timer directory = os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875,", "fwhm = 0.7 sky_level = 1000.0 img = fitter.model( dx, dy, fwhm, z_true,", "fwhm_fit, z_fit # ) # plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2)", "= np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref", "= result.x z_fit = np.array(z_fit) # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit,", "fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2, 3) ax0 = fig.add_subplot(gs[0, 0])", "danish model to produce a test image of rigid-body + M1-surface-Zernike perturbed LSST", "i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( telescope, thx, thy, wavelength,", "the transverse aberration # zernikes since danish uses a transverse aberration ray-hit model.", "ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax, dtype=int)) ax3.legend() plt.show() def plot_dz_results(imgs, mods, dz_fit,", "imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_rigid_perturbation(): \"\"\"Roundtrip using danish", "i, (thx, thy) in enumerate(zip(thxs, thys)): z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength,", "= ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx,", "ax3.set_xticks(range(len(dz_terms))) ax3.set_xticklabels(dz_terms) ax3.legend() plt.show() @timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to", "< 0.4, \"rms %9.3f > 0.4\" % rms # mods = fitter.model( #", "dz_true/wavelength, dz_terms # ) if __name__ == \"__main__\": test_fitter_LSST_fiducial() test_fitter_LSST_rigid_perturbation() test_fitter_LSST_z_perturbation() test_fitter_LSST_kolm() test_fitter_LSST_atm()", "z_true, sky_level=sky_level, flux=5e6 ) # Now guess aberrations are 0.0, and try to", "11) telescope = telescope.withSurface( \"M1\", batoid.Sum([ M1.surface, batoid.Zernike( M1_a, R_outer=M1.obscuration.original.outer, R_inner=M1.obscuration.original.inner ) ])", "point inside 0.05 degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0,", "fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, :]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3.axhline(0, c='k')", "factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory(", "max_nfev=20, verbose=2, args=(binned_img, 4*sky_level) ) t1 = time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\")", "= np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f > %9.3\" % (rms2x2, tol)", "= os.path.dirname(__file__) LSST_obsc_radii = { 'M1_inner': 2.5580033095346875, 'M2_outer': 4.502721059044802, 'M2_inner': 2.3698531889709487, 'M3_outer': 5.4353949343626216,", "danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar = len(thxs) guess =", "6), # linear astigmatism (1, 7), (1, 8) # constant coma ) dz_true", "field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)),", "else: niter = 2 for _ in range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4,", "thy=thy ) dx, dy = 0.0, 0.0 fwhm = 0.7 sky_level = 1000.0", "= np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) #", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) sky_level = data[0]['sky_level'] if __name__ == \"__main__\": niter", "137.51151184228345, 'L2_entrance': 225.63931108752732, 'L2_exit': 236.8641351903567, 'Filter_entrance': 801.6598843836333, 'Filter_exit': 879.4647343264201, 'L3_entrance': 1594.7432961792515, 'L3_exit': 3328.637595923783", "# dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit,", "(1, 10), # constant trefoil (1, 11), # constant spherical (1, 12), (1,", "using GalSim Kolmogorov atmosphere + batoid to produce test image of AOS DOF", "[0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(1234) if __name__ ==", "random double Zernike offsets. Model and fitter run through the same code. \"\"\"", "field angle, so flip based on # that. if np.rad2deg(np.hypot(thx, thy)) > 1.7:", "screen atmosphere + batoid to produce test image of AOS DOF perturbed optics.", "nstar)) ph = rng.uniform(0, 2*np.pi, nstar) thxs, thys = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_refs =", "0.05, \"rms %9.3f > 0.05\" % rms # dxs_fit, dys_fit, fwhm_fit, dz_fit =", "atmosphere + batoid to produce test image of AOS DOF perturbed optics. Model", "# ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 )", "jmax=66, eps=0.61 ) z_refs *= wavelength dz_terms = ( (1, 4), # defocus", "[0.0, 0.0, 0.7] + [0.0]*19 t0 = time.time() result = least_squares( fitter.chi, guess,", "thy)) > 1.7: tol = 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0,", "ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit')", "atol=0.1 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.05,", "thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20,", "wavelength z_perturb = batoid.zernikeTA( telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61", "wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength z_terms = np.arange(4,", "= 0.0, 0.0 fwhm = 0.7 sky_level = 1000.0 img = fitter.model( dx,", "and fitter run through the same code. \"\"\" # Nominal donut mode for", "@timer def test_fitter_LSST_fiducial(): \"\"\" Roundtrip using danish model to produce a test image", "np.array(z_fit) # Optional visualization # mod = fitter.model( # dx_fit, dy_fit, fwhm_fit, z_fit", "degree radius field-of-view thr = np.sqrt(rng.uniform(0, 0.05**2)) ph = rng.uniform(0, 2*np.pi) thx, thy", "obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy", "produce a test image of rigid-body perturbed AuxTel transverse Zernikes. Model and fitter", "# zernikes since danish uses a transverse aberration ray-hit model. z_ref = batoid.zernikeTA(", "= danish.DonutFactory( R_outer=0.6, R_inner=0.2115, obsc_radii=AuxTel_obsc_radii, obsc_motion=AuxTel_obsc_motion, focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory,", "[0, 0, 0.0015]) wavelength = 750e-9 rng = np.random.default_rng(2344) nstar = 10 if", "perturbed optics. Model and fitter run independent code. \"\"\" with open( os.path.join(directory, \"data\",", "atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms %9.3f > 0.1\" %", "same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0, 0.0015]) wavelength", "telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_ref *= wavelength", "def test_dz_fitter_LSST_kolm(): with open( os.path.join(directory, \"data\", \"test_kolm_donuts.pkl\"), 'rb' ) as f: data =", "rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope, thx, thy,", "z_ref)[4:23] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter =", "- dz_ref[term])*wavelength fitter = danish.MultiDonutModel( factory, z_refs=np.array(z_refs)*wavelength, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) nstar", "binning 2x2 binned_fitter = danish.SingleDonutModel( binned_factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy, npix=89 ) binned_img", ".withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1 = telescope['M1'] M1_a = np.zeros(23) M1_a[9:16] =", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) binned_factory = danish.DonutFactory( R_outer=4.18,", "ax3.plot( np.arange(4, jmax), (z_fit-z_true), c='r', label='fit - truth' ) if ylim is None:", "import time from scipy.optimize import least_squares import numpy as np import batoid import", "ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)), np.deg2rad(thr*np.sin(ph)) z_ref = batoid.zernikeTA( telescope,", ".withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) ) # Random point inside 0.05 degree radius field-of-view", "dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5,", "f\" {z_true[i-4]/wavelength:9.3f}\" out += f\" {(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x", "= datum['arr'][::-1, ::-1] z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms,", "< 0.2, \"rms %9.3f > 0.2\" % rms # mods = fitter.model( #", "23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0,", "fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz])", "pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6", "= danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=10e-6 ) fitter = danish.MultiDonutModel( factory,", "data[1:niter]: thx = datum['thx'] thy = datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual']", "nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_refs *= wavelength z_perturbs *= wavelength dz_ref", "atol=1e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=1e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.005*wavelength)", "The R_inner and focal_length here don't quite match what I've # seen elsewhere.", "\"__main__\": niter = 10 else: niter = 1 for _ in range(niter): thr", "fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5,", "fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # Optional visualization # mod =", "fitter.unpack_params(result.x) # mods = fitter.model( # dxs_fit, dys_fit, fwhm_fit, dz_fit # ) #", "dz_fit/wavelength, dz_true/wavelength, rtol=0, atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert", "\"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) .withGloballyShiftedOptic(\"LSSTCamera\", [cam_dx, cam_dy, cam_dz]) .withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) M1", "assert rms < 0.6, \"rms %9.3f > 0.6\" % rms # Try binning", "ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3", "model to produce a test images of rigid-body perturbed LSST transverse Zernikes. Model", "plot_result(binned_img, mod, z_fit/wavelength, z_true/wavelength) np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2))", "< 0.1, \"rms %9.3f > 0.1\" % rms # mods = fitter.model( #", ") z_perturb *= wavelength z_terms = np.arange(4, 12) z_true = (z_perturb - z_ref)[4:12]", ".withLocallyRotatedOptic( \"LSSTCamera\", batoid.RotX(cam_thx)@batoid.RotY(cam_thy) ) ) thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi)", "range(niter): M2_dx, M2_dy = rng.uniform(-2e-4, 2e-4, size=2) M2_dz = rng.uniform(-2e-5, 2e-5) M2_thx, M2_thy", "= result.x z_fit = np.array(z_fit) # Optional visualization # mod = fitter.model( #", "[0, 0, 0.0015] ) wavelength = 750e-9 rng = np.random.default_rng(124) if __name__ ==", "= np.empty((nstar, 67)) z_perturbs = np.empty((nstar, 67)) for i, (thx, thy) in enumerate(zip(thxs,", "atol=0.2 ) rms = np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.4,", "focal_length=20.8, pixel_scale=10e-6 ) fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 )", "thys=thys ) dxs = rng.uniform(-0.5, 0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm", "eps=0.2115/0.6 ) z_ref *= wavelength # The zernikes of the perturbed telescope. I.e.,", "fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess = [0.0, 0.0, 0.7]+[0.0]*19 result = least_squares(", "{rms:9.3f} waves\") assert rms < 0.05, \"rms %9.3f > 0.05\" % rms #", "niter = 2 for datum in data[1:niter]: thx = datum['thx'] thy = datum['thy']", "numpy as np import batoid import danish from test_helpers import timer directory =", ") guess = [0.0, 0.0, 0.7] + [0.0]*19 result = least_squares( fitter.chi, guess,", "1000.0 img = fitter.model( dx, dy, fwhm, z_true, sky_level=sky_level, flux=5e6 ) guess =", "dx_fit, dy_fit, fwhm_fit, z_fit # ) # plot_result(img, mod, z_fit/wavelength, z_true/wavelength) # One", ") thr = np.sqrt(rng.uniform(0, 1.8**2)) ph = rng.uniform(0, 2*np.pi) thx, thy = np.deg2rad(thr*np.cos(ph)),", "rtol=0, atol=tol*wavelength) rms2x2 = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms2x2 < 2*tol, \"rms %9.3f > %9.3\"", "dys_fit, fwhm_fit, dz_fit # ) # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms", "rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2))", "telescope = ( fiducial_telescope .withGloballyShiftedOptic(\"M2\", [M2_dx, M2_dy, M2_dz]) .withLocallyRotatedOptic( \"M2\", batoid.RotX(M2_thx)@batoid.RotY(M2_thy) ) )", "imgs = fitter.model( dxs, dys, fwhm, dz_true, sky_levels=sky_levels, fluxes=fluxes ) guess = [0.0]*nstar", "jmax), (z_fit-z_true), c='r', label='fit - truth' ) if ylim is None: ylim =", "np.rad2deg(np.hypot(thx, thy)) > 1.7: tol = 0.7 else: tol = 0.25 np.testing.assert_allclose(fwhm_fit, fwhm,", "# imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) @timer def test_dz_fitter_LSST_kolm(): with open(", "*= wavelength z_perturbs *= wavelength dz_ref = batoid.analysis.doubleZernike( fiducial_telescope, np.deg2rad(1.8), wavelength, rings=10, kmax=10,", "\"__main__\": niter = 10 else: niter = 1 for _ in range(niter): M2_dx,", "0.5, nstar) dys = rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels =", "# ) # plot_dz_results( # imgs, mods, dz_fit/wavelength, dz_true/wavelength, dz_terms # ) if", "'L3_exit': 3328.637595923783 } AuxTel_obsc_radii = { 'Baffle_M2c_inner': 0.2115 } AuxTel_obsc_motion = { 'Baffle_M2c_inner':", "fiducial LSST transverse Zernikes plus random double Zernike offsets. Model and fitter run", "z_terms = np.arange(4, 23) fitter = danish.SingleDonutModel( factory, z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy )", "np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms", "z_ref *= wavelength # The zernikes of the perturbed telescope. I.e., the \"truth\".", "to produce test image of AOS DOF perturbed optics. Model and fitter run", "fitter = danish.SingleDonutModel( factory, z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy, npix=255 ) dx, dy =", "fig = plt.figure(constrained_layout=True, figsize=(10, 12)) gs = fig.add_gridspec(len(imgs)+3, 3) for i, (img, mod)", "(1, 12), (1, 13), # second astigmatism (1, 14), (1, 15), # quatrefoil", "open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) wavelength =", ") nstar = 10 thr = np.sqrt(rng.uniform(0, 1.8**2, nstar)) ph = rng.uniform(0, 2*np.pi,", "a test image of rigid-body perturbed AuxTel transverse Zernikes. Model and fitter run", "< 0.1, \"rms %9.3f > 0.02\" % rms @timer def test_fitter_LSST_kolm(): \"\"\"Roundtrip using", "0.0, 0.7] + [0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3,", "1]) ax2 = fig.add_subplot(gs[i, 2]) ax0.imshow(img/np.sum(img)) ax1.imshow(mod/np.sum(mod)) ax2.imshow(img/np.sum(img) - mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:,", "[0.0]*nstar + [0.0]*nstar + [0.7] + [0.0]*len(dz_terms) result = least_squares( fitter.chi, guess, jac=fitter.jac,", "verbose=2, args=(img, sky_level) ) for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\"", "binned_factory = danish.DonutFactory( R_outer=4.18, R_inner=2.5498, obsc_radii=LSST_obsc_radii, obsc_motion=LSST_obsc_motion, focal_length=10.31, pixel_scale=20e-6 ) if __name__ ==", "z_refs[i] = batoid.zernikeTA( fiducial_telescope, thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 )", "model to produce a test image of rigid-body perturbed AuxTel transverse Zernikes. Model", "\"\"\"Roundtrip using GalSim Kolmogorov atmosphere + batoid to produce test image of AOS", "= rng.uniform(-0.5, 0.5, nstar) fwhm = rng.uniform(0.5, 1.5) sky_levels = [1000.0]*nstar fluxes =", "through the same code. \"\"\" telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\") telescope = telescope.withGloballyShiftedOptic(\"Detector\", [0, 0,", "{(result.x[i-1]-z_true[i-4])/wavelength:9.3f}\" print(out) dx_fit, dy_fit, fwhm_fit, *z_fit = result.x z_fit = np.array(z_fit) # Optional", "datum['thy'] z_ref = datum['z_ref'] z_actual = datum['z_actual'] img = datum['arr'][::-1, ::-1] z_terms =", "thx, thy, wavelength, nrad=20, naz=120, reference='chief', jmax=66, eps=0.61 ) z_perturbs[i] = batoid.zernikeTA( telescope,", "\"rms %9.3f > 0.2\" % rms # mods = fitter.model( # dxs_fit, dys_fit,", "(1, 17), (1, 18), (1, 19), (1, 20), (1, 21), (1, 22) )", "else: niter = 2 for _ in range(niter): # Randomly perturb M2 alignment", "z_ref=z_ref, z_terms=z_terms, thx=thx, thy=thy ) dx, dy = rng.uniform(-0.5, 0.5, size=2) fwhm =", "verbose=2, args=(img, sky_level) ) t1 = time.time() t1x1 = t1 - t0 z_true", "max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 12): out = f\"{i:2d}", "len(z_fit)+4 import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True, figsize=(10, 7)) gs = fig.add_gridspec(2,", "= (z_actual-z_ref)[4:23]*wavelength for i in range(4, 23): out = f\"{i:2d} {result.x[i-1]/wavelength:9.3f}\" out +=", ") as f: data = pickle.load(f) wavelength = data[0]['wavelength'] factory = danish.DonutFactory( R_outer=4.18,", "is None: ylim = -0.6, 0.6 ax3.set_ylim(*ylim) ax3.set_xlabel(\"Zernike index\") ax3.set_ylabel(\"Residual (Waves)\") ax3.set_xticks(np.arange(4, jmax,", "waves\") assert rms < 0.2, \"rms %9.3f > 0.2\" % rms # mods", "atol=5e-2) np.testing.assert_allclose(z_fit, z_true, rtol=0, atol=0.05*wavelength) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) assert rms < 0.1, \"rms", "\"\"\" with open( os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f)", "danish.MultiDonutModel( factory, z_refs=z_refs, dz_terms=dz_terms, field_radius=np.deg2rad(1.8), thxs=thxs, thys=thys ) guess = [0.0]*nstar + [0.0]*nstar", "z_true/wavelength) np.testing.assert_allclose(dx_fit, dx, rtol=0, atol=5e-2) np.testing.assert_allclose(dy_fit, dy, rtol=0, atol=5e-2) np.testing.assert_allclose(fwhm_fit, fwhm, rtol=0, atol=5e-2)", "assert rms < 0.1, \"rms %9.3f > 0.02\" % rms @timer def test_fitter_LSST_kolm():", "[0.0, 0.0, 0.7]+[0.0]*19 result = least_squares( fitter.chi, guess, jac=fitter.jac, ftol=1e-3, xtol=1e-3, gtol=1e-3, max_nfev=20,", "os.path.join(directory, \"data\", \"test_atm_donuts.pkl\"), 'rb' ) as f: data = pickle.load(f) factory = danish.DonutFactory(", "= time.time() print(f\"2x2 fit time: {t1-t0:.3f} sec\") dx_fit, dy_fit, fwhm_fit, *z_fit = binned_result.x", "Zernikes. Model and fitter run through the same code. \"\"\" fiducial_telescope = batoid.Optic.fromYaml(\"LSST_i.yaml\")", "fwhm_fit, *z_fit = binned_result.x z_fit = np.array(z_fit) # mod = binned_fitter.model( # dx_fit,", "np.testing.assert_allclose( z_fit/wavelength, z_true/wavelength, rtol=0, atol=0.5 ) rms = np.sqrt(np.sum(((z_true-z_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\")", "z_ref=z_ref*wavelength, z_terms=z_terms, thx=thx, thy=thy ) guess = [0.0, 0.0, 0.7] + [0.0]*19 t0", "fwhm, z_true, sky_level=sky_level, flux=5e6 ) # Now guess aberrations are 0.0, and try", "= np.sqrt(np.sum(((dz_true-dz_fit)/wavelength)**2)) print(f\"rms = {rms:9.3f} waves\") assert rms < 0.1, \"rms %9.3f >", "xtol=1e-3, gtol=1e-3, max_nfev=20, verbose=2, args=(img, sky_level) ) for i in range(4, 12): out", "0.05\" % rms # dxs_fit, dys_fit, fwhm_fit, dz_fit = fitter.unpack_params(result.x) # mods =", "mod/np.sum(mod)) ax3 = fig.add_subplot(gs[-3:, :]) ax3.axhline(0, c='k', alpha=0.1) ax3.plot(dz_fit, c='b', label='fit') ax3.plot(dz_true, c='k'," ]
[ "row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in data: for title", "#!/usr/bin/env python3 from pathlib import Path import requests from bs4 import BeautifulSoup page", "[data_from(item) for item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row", "data_from(item): title = item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data = [ [data_from(item)", "as out: def data_from(item): title = item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data", "return title.text table_tag = tree.select(\"table\")[1] data = [ [data_from(item) for item in row_data.select(\"td\")]", "= [ [data_from(item) for item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\")", "title.text table_tag = tree.select(\"table\")[1] data = [ [data_from(item) for item in row_data.select(\"td\")] for", "= requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" /", "\"songs.csv\", \"w\", newline=\"\") as out: def data_from(item): title = item.select(\"a\")[1] return title.text table_tag", "row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in data: for title in row:", "\"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\") as out: def data_from(item): title =", "tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\", \"w\",", "\"assets\" / \"songs.csv\", \"w\", newline=\"\") as out: def data_from(item): title = item.select(\"a\")[1] return", "= item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data = [ [data_from(item) for item", "bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with", "for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in data: for title in", "[ [data_from(item) for item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for", "item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in data:", "= BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\")", "in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in data: for", "data = [ [data_from(item) for item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ]", "table_tag = tree.select(\"table\")[1] data = [ [data_from(item) for item in row_data.select(\"td\")] for row_data", "def data_from(item): title = item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data = [", "BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") /", "Path import requests from bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree", "tree.select(\"table\")[1] data = [ [data_from(item) for item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\")", "/ \"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\") as out: def data_from(item): title", "pathlib import Path import requests from bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\"", ") tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\",", "page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\"", "import requests from bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree =", "\"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\" /", "requests from bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content,", "BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\") as", "out: def data_from(item): title = item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data =", "from pathlib import Path import requests from bs4 import BeautifulSoup page = requests.get(", "/ \"songs.csv\", \"w\", newline=\"\") as out: def data_from(item): title = item.select(\"a\")[1] return title.text", "title = item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data = [ [data_from(item) for", "for item in row_data.select(\"td\")] for row_data in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in", "/ \"assets\" / \"songs.csv\", \"w\", newline=\"\") as out: def data_from(item): title = item.select(\"a\")[1]", "newline=\"\") as out: def data_from(item): title = item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1]", "\"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\") as out:", "in table_tag.select(\"tr\") ] out.write(\"name\\n\") for row in data: for title in row: out.write(f\"{title}\\n\")", "python3 from pathlib import Path import requests from bs4 import BeautifulSoup page =", "with open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\") as out: def", "\"w\", newline=\"\") as out: def data_from(item): title = item.select(\"a\")[1] return title.text table_tag =", "import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\")", "from bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\")", "open(Path(\"src\") / \"turbot\" / \"assets\" / \"songs.csv\", \"w\", newline=\"\") as out: def data_from(item):", "= tree.select(\"table\")[1] data = [ [data_from(item) for item in row_data.select(\"td\")] for row_data in", "item.select(\"a\")[1] return title.text table_tag = tree.select(\"table\")[1] data = [ [data_from(item) for item in", "import Path import requests from bs4 import BeautifulSoup page = requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" )", "requests.get( \"https://animalcrossing.fandom.com/wiki/K.K._Slider_song_list_(New_Horizons)\" ) tree = BeautifulSoup(page.content, \"lxml\") with open(Path(\"src\") / \"turbot\" / \"assets\"" ]
[ "* (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\")", "print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") # input suhu dalam fahrenheit f =", "digunakan C = 5 * (F-32)/9 # menampilkan informasi program print(\"Konversi Suhu dari", "program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") # input suhu dalam fahrenheit f", "suhu (Fahrenheit): \")) # melakukan konversi suhu ke Celcius c = 5 *", "konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\") os.system(\"pause\") if __name__ == \"__main__\":", "os def main(): # rumus yang digunakan C = 5 * (F-32)/9 #", "= 5 * (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\",", "rumus yang digunakan C = 5 * (F-32)/9 # menampilkan informasi program print(\"Konversi", "main(): # rumus yang digunakan C = 5 * (F-32)/9 # menampilkan informasi", "informasi program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") # input suhu dalam fahrenheit", "5 * (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c,", "= 5 * (F-32)/9 # menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit ke", "menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") # input suhu dalam", "# melakukan konversi suhu ke Celcius c = 5 * (f-32)/9 # menampilkan", "c = 5 * (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius", "import os def main(): # rumus yang digunakan C = 5 * (F-32)/9", "Celcius)\\n\") # input suhu dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \")) #", "suhu dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi suhu", "dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi suhu ke", "f = float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi suhu ke Celcius c", "float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi suhu ke Celcius c = 5", "suhu ke Celcius c = 5 * (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit", "input suhu dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi", "Suhu dari Fahrenheit ke Celcius)\\n\") # input suhu dalam fahrenheit f = float(input(\"Masukan", "* (F-32)/9 # menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") #", "C = 5 * (F-32)/9 # menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit", "# menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\") os.system(\"pause\") if", "print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\") os.system(\"pause\") if __name__ == \"__main__\": main()", "hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\") os.system(\"pause\") if __name__ ==", "menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\") os.system(\"pause\") if __name__", "# menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") # input suhu", "yang digunakan C = 5 * (F-32)/9 # menampilkan informasi program print(\"Konversi Suhu", "# rumus yang digunakan C = 5 * (F-32)/9 # menampilkan informasi program", "def main(): # rumus yang digunakan C = 5 * (F-32)/9 # menampilkan", "melakukan konversi suhu ke Celcius c = 5 * (f-32)/9 # menampilkan hasil", "konversi suhu ke Celcius c = 5 * (f-32)/9 # menampilkan hasil konversi", "(f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\", f) print(\"Celcius \\t:\", c, \"\\n\") os.system(\"pause\")", "Fahrenheit ke Celcius)\\n\") # input suhu dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit):", "Celcius c = 5 * (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\", f)", "(F-32)/9 # menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\") # input", "dari Fahrenheit ke Celcius)\\n\") # input suhu dalam fahrenheit f = float(input(\"Masukan suhu", "\")) # melakukan konversi suhu ke Celcius c = 5 * (f-32)/9 #", "ke Celcius c = 5 * (f-32)/9 # menampilkan hasil konversi print(\"Fahrenheit \\t:\",", "(Fahrenheit): \")) # melakukan konversi suhu ke Celcius c = 5 * (f-32)/9", "fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi suhu ke Celcius", "<gh_stars>1-10 import os def main(): # rumus yang digunakan C = 5 *", "= float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan konversi suhu ke Celcius c =", "5 * (F-32)/9 # menampilkan informasi program print(\"Konversi Suhu dari Fahrenheit ke Celcius)\\n\")", "# input suhu dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \")) # melakukan", "ke Celcius)\\n\") # input suhu dalam fahrenheit f = float(input(\"Masukan suhu (Fahrenheit): \"))" ]
[ ") vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 =", ") self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), ) self.assertEqual(", "\"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\")", "= \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out,", "1, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1", "os import unittest import cluster_vcf_records from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir", "total_alleles=5 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "(4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test", "chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test", "vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two", "= vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [", "tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for ref,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "(1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), ) self.assertEqual( (0, 5,", "\"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7", "def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT = alt test_dict", "record_list, 1, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1,", "shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 =", "alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants", "3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), ) self.assertEqual( (4, 4, 4),", "record_list, 2, 100, total_sites=2 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4,", "record_list, 0, 3, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "2, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1", "1, total_alleles=1 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2", ") chunker.make_split_files() to_merge = {} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), ) self.assertEqual( (0, 5, 5),", "0, 1, total_alleles=10 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), ) self.assertEqual( (0,", "= vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), ) self.assertEqual( (4, 5, 5),", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "[FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles = 24", "), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), )", "(3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), ) self.assertEqual( (4, 5,", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "2, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), ) self.assertEqual( (3, 5, 5),", "def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa =", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\"", "self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), ) self.assertEqual( (5,", "20, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records)", "shutil.rmtree(tmp_out) # Test with two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2,", "FakeVcf: def __init__(self, alt): self.ALT = alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"),", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), ) self.assertEqual( (0,", "), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), )", "\"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", "0, 2, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), ) self.assertEqual( (1, 5, 5),", ") self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), ) self.assertEqual(", "3, total_sites=8 ), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1", "total_sites=2 ), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ),", "\"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines", "gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split", "(4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), ) self.assertEqual( (5, 5,", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "0, 3, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "import shutil import os import unittest import cluster_vcf_records from minos import vcf_chunker this_dir", "# These records caused minos error because variant at 800 # was included", "chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header,", "(0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), ) self.assertEqual( (0, 5,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3,", "self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), ) self.assertEqual( (0,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), ) self.assertEqual( (2, 5, 5),", "4, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4", "), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), )", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), ) self.assertEqual(", "record_list, 5, 20, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), ) self.assertEqual( (0, 4, 4),", "record_list, 0, 4, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), )", "1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), ) self.assertEqual( (0, 2, 3),", "test_make_split_files_2(self): \"\"\"test make_split_files with different input from previous test\"\"\" # These records cause", "record_list, 0, 1, total_alleles=8 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "2, total_sites=1 ), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1", "cluster_vcf_records from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\")", ") vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines =", "), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), )", "record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"),", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), ) self.assertEqual( (0, 1,", "self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header)", "3, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2", ") vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 =", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), )", "1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2", "5, 1, total_sites=1 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1,", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker =", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\"", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), ) self.assertEqual(", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile", "\"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT", "= alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], }", "total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ),", "total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ),", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), )", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), ) self.assertEqual(", "record_list, 5, 21, total_sites=2 ), ) # These records caused minos error because", "\"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2", "1, 1, total_sites=6 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1,", "total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ),", "), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), )", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\",", "vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5,", "0, 1, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "total_sites=1 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ),", "are test data from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\"", "shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle))", "total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ),", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ),", "5, 18, total_sites=2 ), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19,", "# when merging because the index was wrong. # They are test data", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), ) self.assertEqual( (0, 0,", "self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split =", "if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" )", "(5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), ) self.assertEqual( (5, 5,", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), ) self.assertEqual( (0, 2, 3),", "a minos bug. Last record was not being used # when merging because", "at 800 # was included in the last split file, but the use_end_index", "self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3],", ") self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), ) self.assertEqual(", ") self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), ) self.assertEqual(", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles = 24 ( got_variants,", "alt): self.ALT = alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ),", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), ) # These", "Last record was not being used # when merging because the index was", "was wrong. # They are test data from multi_sample_pipeline tests infile = os.path.join(data_dir,", "(0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), ) self.assertEqual( (0, 5,", "self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), ) self.assertEqual( (0,", "if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, )", "os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self,", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), ) self.assertEqual( (0,", "self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files,", "included in the last split file, but the use_end_index was at # position", ") self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), ) def", "1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1", "being used # when merging because the index was wrong. # They are", "\"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, )", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), ) self.assertEqual(", "variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") )", "(4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), ) self.assertEqual( (3, 4,", "test data from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa", "3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), ) self.assertEqual( (0, 4, 4),", "total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ),", "total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ),", "record_list, 4, 100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir,", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\",", "os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker", "vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", "len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir,", "record_list, 1, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1,", "gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] =", "4, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2", "__init__(self, alt): self.ALT = alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\":", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), ) self.assertEqual( (0, 0, 1),", ") self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), ) self.assertEqual(", "0, 1, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files))", "total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ),", "record_list, 5, 19, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "(0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), ) self.assertEqual( (0, 1,", "(0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), ) self.assertEqual( (0, 5,", "1, total_alleles=2 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3", "1, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2,", "not being used # when merging because the index was wrong. # They", "import unittest import cluster_vcf_records from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir =", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), ) self.assertEqual( (0, 1,", "0, 1, total_alleles=2 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3),", "vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records =", "\"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files()", ") self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), ) self.assertEqual(", "FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles = 24 (", "(3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), ) self.assertEqual( (3, 5,", "the last split file, but the use_end_index was at # position of the", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), ) self.assertEqual(", "chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa,", "2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), ) self.assertEqual( (0, 2, 2),", "minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase):", "0, 100, total_sites=2 ), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100,", "0, 3, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "_chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "at 610. So the one at 800 was not getting used. record_list =", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), ) # These records caused minos", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), ) self.assertEqual( (0, 5, 5),", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), )", "\"\"\"test make_split_files with different input from previous test\"\"\" # These records cause a", "len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads chunker =", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\")", "got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta)", "os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class", "self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits,", "test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants =", "total_alleles=6 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ),", "0, 1, total_sites=2 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), ) self.assertEqual( (0,", "1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), ) self.assertEqual( (2, 3, 3),", "0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 2),", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records", "self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split,", "total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ),", "= os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def", "file, but the use_end_index was at # position of the variant at 610.", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\")", "vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for ref, split_list", "0, 1, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), ) self.assertEqual(", "6, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2", "2, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3", "total_sites=1 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ),", ") vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 =", "1, total_sites=1 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2", "vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord(", "3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), ) self.assertEqual( (0, 4, 5),", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", "data from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa =", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records =", "0, 1, total_alleles=9 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), ) self.assertEqual( (0,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), ) self.assertEqual( (0, 5,", "] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), )", ") self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), ) self.assertEqual(", "self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), ) self.assertEqual( (4,", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile)", "gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), )", "total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ),", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "1, 15, total_sites=1 ), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16,", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), ) self.assertEqual( (0, 0, 1),", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), ) self.assertEqual(", "), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), )", ") self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), ) self.assertEqual(", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), ) self.assertEqual( (0,", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), ) self.assertEqual( (3,", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), ) self.assertEqual(", "# They are test data from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out", "total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ),", "total_sites=1 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ),", "self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), ) self.assertEqual( (4,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), ) self.assertEqual( (0, 5, 5),", "), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), )", "self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), ) self.assertEqual( (5,", "total_sites=2 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ),", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), )", "test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT = alt test_dict =", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), ) self.assertEqual( (0, 1, 2),", "self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, )", "self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "record_list, 5, 18, total_sites=2 ), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "0, 4, total_sites=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1,", "(0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), ) self.assertEqual( (0, 1,", ") self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), ) self.assertEqual(", "record_list, 0, 2, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", ") self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), )", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), ) self.assertEqual( (4,", "), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), )", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), ) self.assertEqual( (4, 5, 5),", "1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), ) self.assertEqual( (0, 5, 5),", "self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads chunker", "record_list, 0, 1, total_alleles=5 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "0, 4, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", "(0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), ) self.assertEqual( (0, 3,", "import os import unittest import cluster_vcf_records from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__))", "(0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), ) self.assertEqual( (0, 3,", ") self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), ) self.assertEqual(", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), )", "class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT =", "), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), )", "(0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), ) self.assertEqual( (0, 4,", "), ) # These records caused minos error because variant at 800 #", "chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "record_list, 0, 4, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header,", "self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), ) self.assertEqual( (0,", "os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3,", "record_list, 0, 1, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "(0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), ) self.assertEqual( (0, 5,", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), )", "3, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6", "because the index was wrong. # They are test data from multi_sample_pipeline tests", "got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out,", "for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in split_list] tmp_vcf_out", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), ) self.assertEqual( (0, 2,", "total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ),", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), ) self.assertEqual( (0, 1, 2),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different input from previous", "2, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2", "vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), )", "\"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\",", "two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, )", "\"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\"", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "record_list, 5, 1, total_sites=1 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index)", "self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def", "vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self):", "vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord(", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), ) self.assertEqual( (0,", "self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), ) self.assertEqual( (0,", "record_list, 0, 1, total_alleles=11 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "0, 4, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "0, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), ) #", "self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header)", "0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), ) self.assertEqual( (0, 1, 3),", "os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "record_list, 0, 1, total_sites=2 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), ) self.assertEqual( (0,", "= [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ]", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), )", "0, 1, total_alleles=4 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), ) self.assertEqual( (2,", "total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ),", "but the use_end_index was at # position of the variant at 610. So", "self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), ) def test_make_split_files(self):", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5],", "os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker(", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records)", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records)", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker", "4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), ) self.assertEqual( (4, 4, 4),", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), ) self.assertEqual( (0,", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), ) self.assertEqual(", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\"", "5, 19, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20,", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), ) self.assertEqual( (0, 0, 1),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "shutil import os import unittest import cluster_vcf_records from minos import vcf_chunker this_dir =", "tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out)", "[x.filename for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge, tmp_vcf_out) self.assertTrue(filecmp.cmp(vcf_to_split, tmp_vcf_out, shallow=False))", "vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker", "record_list, 0, 2, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "These records caused minos error because variant at 800 # was included in", "self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT = alt", "\"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile,", "4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), ) self.assertEqual( (0, 5, 5),", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), ) self.assertEqual( (0,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out", "position of the variant at 610. So the one at 800 was not", "0, 4, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", ") self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), ) self.assertEqual(", "len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta", "self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), ) self.assertEqual( (5,", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\")))", "records caused minos error because variant at 800 # was included in the", "gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header)", "self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out)", "len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads chunker = vcf_chunker.VcfChunker( tmp_out,", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines,", "= os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\"", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "with two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ),", "vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), )", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), ) self.assertEqual( (0, 1,", "(4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), ) self.assertEqual( (4, 4,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), ) self.assertEqual( (0, 0, 2),", "bug. Last record was not being used # when merging because the index", "\"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\")", "4, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1,", "(0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), ) self.assertEqual( (0, 1,", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), )", "record_list, 1, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "use_end_index was at # position of the variant at 610. So the one", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile =", "0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3),", "3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), ) self.assertEqual( (0,", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "= vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), ) self.assertEqual( (0, 5, 5),", ") vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 =", "2, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4", "cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" )", "total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out =", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header,", "4, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6", "record_list, 4, 1, total_sites=1 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4,", "at 800 was not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"),", "variant at 610. So the one at 800 was not getting used. record_list", "), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), )", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "\"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\"", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\")", "self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), ) self.assertEqual( (0,", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "record_list, 0, 2, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), ) self.assertEqual( (0,", "1, total_sites=1 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1", "7, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2", "total_sites=2 ), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ),", "\"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge", "os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3", "the one at 800 was not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"),", "= vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records", "), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), )", "vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", ") self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), )", "1, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), ) self.assertEqual( (0, 5, 5),", "record_list, 0, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), ) self.assertEqual( (0, 5, 5),", "self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") )", "tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, )", "got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out,", "1, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8", "total_sites=1 ), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ),", "total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ),", "with different input from previous test\"\"\" # These records cause a minos bug.", ") self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), ) self.assertEqual(", "0, 2, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles = 24 ( got_variants, got_alleles, ) =", "), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), )", "4, total_sites=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1", "in the last split file, but the use_end_index was at # position of", "vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord(", "# Test with two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200,", "test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir =", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), ) self.assertEqual( (0, 5,", "total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ),", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), ) self.assertEqual( (0, 1, 2),", "total_alleles=1 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ),", "), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), )", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "record_list, 5, 6, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", ") self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), ) self.assertEqual(", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), ) self.assertEqual(", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), ) self.assertEqual( (0, 2,", "18, total_sites=2 ), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2", "error because variant at 800 # was included in the last split file,", "make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if", "cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" )", "), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), )", "vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord(", "os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord(", "record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1),", "\"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", "0, 1, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ),", ") self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), ) self.assertEqual(", ") self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), ) self.assertEqual(", "infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out):", "self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(", "tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), )", "chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files)", "1, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5", "1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1", "wrong. # They are test data from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\")", "at # position of the variant at 610. So the one at 800", "to_merge = {} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2),", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ),", "), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), )", "), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), )", "total_alleles=9 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ),", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records", "\"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT = alt test_dict = {", "\"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out,", "unittest import cluster_vcf_records from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir,", "(4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), ) self.assertEqual( (4, 5,", "total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ),", "total_alleles=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ),", "19, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\"", "os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge =", "(0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), ) self.assertEqual( (0, 3,", "self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different input from previous test\"\"\"", "1, total_alleles=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8", "= os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out)", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different input from previous test\"\"\" #", "3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), ) self.assertEqual( (0, 0, 1),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), ) # These records caused minos error", "5, 4, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5,", "in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge,", "got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4,", "21, total_sites=2 ), ) # These records caused minos error because variant at", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "record_list, 0, 2, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", ") self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), ) self.assertEqual(", "= os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out)", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header,", "vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\"", "total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ),", "2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), ) self.assertEqual( (0, 3, 3),", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), ) self.assertEqual( (0,", "import filecmp import shutil import os import unittest import cluster_vcf_records from minos import", "3, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), )", "input from previous test\"\"\" # These records cause a minos bug. Last record", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile,", "import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def", "= { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), ) # These records", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), ) self.assertEqual(", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), ) self.assertEqual( (0, 5,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), ) self.assertEqual( (0, 0, 3),", "record_list, 0, 4, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "last split file, but the use_end_index was at # position of the variant", "1, total_alleles=12 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "(0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), ) self.assertEqual( (2, 3,", "os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records", "# position of the variant at 610. So the one at 800 was", "def __init__(self, alt): self.ALT = alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")],", "self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ),", "got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\"", "\"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5,", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), ) self.assertEqual( (0, 2, 2),", "record_list, 0, 1, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), ) self.assertEqual( (0, 3, 4),", "vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1,", "ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\")", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out,", "4, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7", ") self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), )", "vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7],", ") self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), ) self.assertEqual(", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), ) self.assertEqual(", "self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), ) self.assertEqual( (3,", "] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), ) self.assertEqual(", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\")", "os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files()", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), ) self.assertEqual( (0, 5, 5),", ") self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), )", "2, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8", "self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), ) self.assertEqual( (3,", "self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), ) self.assertEqual( (0,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), ) self.assertEqual( (0, 5,", "5, 17, total_sites=2 ), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18,", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") )", "x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge, tmp_vcf_out) self.assertTrue(filecmp.cmp(vcf_to_split, tmp_vcf_out, shallow=False)) os.unlink(tmp_vcf_out) shutil.rmtree(tmp_outdir)", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files))", "total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ),", "0, 1, total_alleles=3 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "total_sites=2 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ),", "= vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {}", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), ) self.assertEqual( (0,", "from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir,", "\"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), ) self.assertEqual(", "vcf3, vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header)", "), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), ) self.assertEqual( (0, 5,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ),", "3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), ) self.assertEqual( (0, 4, 5),", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records)", "got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines,", ") self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), ) self.assertEqual(", "= os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker(", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0,", "chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length,", "[ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual(", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), ) self.assertEqual( (0, 1,", "total_sites=8 ), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ),", "5, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header,", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "4, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3", "total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ),", "), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), )", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), )", "got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list", "the use_end_index was at # position of the variant at 610. So the", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "record_list, 0, 1, total_alleles=4 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "0, 2, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), ) self.assertEqual( (2,", "0, 4, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir,", ") self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), ) self.assertEqual(", "1, total_alleles=11 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records", "), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), )", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "100, total_sites=2 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2", "self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), ) self.assertEqual( (0,", "\"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker =", "chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test", "0, 1, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different input from previous test\"\"\" # These", "total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_alleles=4 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ),", "header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa,", "chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files)", "chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2,", "used # when merging because the index was wrong. # They are test", "2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), ) self.assertEqual( (0, 3, 3),", "record_list, 0, 2, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out)", "0, 2, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), ) self.assertEqual( (4,", "(0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), ) self.assertEqual( (0, 1,", "2, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2", "2, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7", "not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual(", "\"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5,", "0, 2, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "4, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5", "total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ),", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), )", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "0, 1, total_alleles=6 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "the variant at 610. So the one at 800 was not getting used.", "got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header,", "self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), ) self.assertEqual( (0,", "chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different input", "These records cause a minos bug. Last record was not being used #", ") header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile,", "class FakeVcf: def __init__(self, alt): self.ALT = alt test_dict = { \"chrom1\": [FakeVcf(\"123\"),", "2, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "= cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\"", "2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), ) self.assertEqual( (0, 3, 4),", "), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), )", "(0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), ) self.assertEqual( (0, 2,", "record_list, 0, 1, total_alleles=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), ) self.assertEqual( (0, 0, 1),", "record_list, 0, 2, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "record_list, 0, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records =", "def test_make_split_files_2(self): \"\"\"test make_split_files with different input from previous test\"\"\" # These records", "800 was not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"),", "self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile,", "self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), ) self.assertEqual( (0,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), ) self.assertEqual( (0, 0,", "= \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\"", "total_sites=2 ), ) # These records caused minos error because variant at 800", "4, 2, total_sites=1 ), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), ) self.assertEqual( (0, 0,", "record_list, 4, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "of the variant at 610. So the one at 800 was not getting", "test\"\"\" # These records cause a minos bug. Last record was not being", "chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def", "16, total_sites=1 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6", "record_list, 0, 1, total_alleles=1 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "{ \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles", "because variant at 800 # was included in the last split file, but", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), )", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), ) self.assertEqual( (0, 1,", "tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if", "(0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), ) self.assertEqual( (0, 3,", "self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) # Test with two threads chunker = vcf_chunker.VcfChunker(", "0, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), ) self.assertEqual( (4, 4,", "record_list, 0, 3, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), )", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1", "[ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1,", "record_list, 0, 4, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records)", "ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in split_list] tmp_vcf_out =", "(5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), ) self.assertEqual( (4, 5,", "total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ),", "(0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), ) self.assertEqual( (0, 4,", "), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), )", "was included in the last split file, but the use_end_index was at #", "24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self):", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "(2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), ) self.assertEqual( (4, 4,", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), ) self.assertEqual( (3,", "), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), )", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7, total_sites=2 ), ) self.assertEqual( (3, 5, 5),", "0, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta,", "2, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5", "(0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), ) self.assertEqual( (0, 2,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", ") vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ]", "\"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files()", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), ) self.assertEqual( (0, 5, 5),", "), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), )", "0, 1, total_alleles=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), ) self.assertEqual( (0, 3, 3),", "cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" )", "] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle))", "record_list, 1, 1, total_sites=6 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4,", "(0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), ) self.assertEqual( (0, 5,", "total_sites=1 ), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ),", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), ) self.assertEqual( (4, 5, 5),", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), ) self.assertEqual( (0, 1, 2),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", ") self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), ) self.assertEqual(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=6 ), ) self.assertEqual(", "\"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ),", "self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), ) self.assertEqual( (4,", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "4, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), )", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\")))", "make_split_files with different input from previous test\"\"\" # These records cause a minos", "got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6],", "5, 20, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21,", "[FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles = 24 ( got_variants, got_alleles, )", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), ) self.assertEqual( (0,", "record_list, 0, 3, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), ) self.assertEqual( (0, 0,", "self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), ) self.assertEqual( (4, 5, 5),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_alleles=10 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ),", "3, total_sites=1 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2", "5 expect_alleles = 24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles,", "4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), ) self.assertEqual( (3, 4, 5),", "vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records)", "test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\"", "record_list, 0, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), ) self.assertEqual( (0, 0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_alleles=3 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ),", "ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), ) self.assertEqual( (4, 4, 4),", "(0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), ) self.assertEqual( (0, 0,", "= os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 =", "record_list, 0, 3, total_sites=8 ), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "filecmp import shutil import os import unittest import cluster_vcf_records from minos import vcf_chunker", "cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" )", "got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4],", "ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for ref, split_list in", "\"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles = 24 ( got_variants, got_alleles,", "_total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt): self.ALT = alt test_dict = { \"chrom1\":", "one at 800 was not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"),", "self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different input from", "def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), ) self.assertEqual( (0, 2, 2),", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records =", "self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7],", "variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for ref, split_list in chunker.vcf_split_files.items():", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), )", "infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out):", "shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle))", "total_alleles=2 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), )", "total_sites=6 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ),", "flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines,", "5, 5, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6,", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") )", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), ) self.assertEqual(", "5, 21, total_sites=2 ), ) # These records caused minos error because variant", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), ) self.assertEqual( (0, 5,", "record_list, 5, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "different input from previous test\"\"\" # These records cause a minos bug. Last", "vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out,", "threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"]))", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "was at # position of the variant at 610. So the one at", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2,", "for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge, tmp_vcf_out) self.assertTrue(filecmp.cmp(vcf_to_split, tmp_vcf_out, shallow=False)) os.unlink(tmp_vcf_out)", "1, total_alleles=10 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11", "[ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "1, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3,", "flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"]))", "(0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), ) self.assertEqual( (0, 4,", "self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta =", "0, 1, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() to_merge = {} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref]", "total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ),", "record_list, 5, 4, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "(4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), ) self.assertEqual( (4, 5,", "was not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ]", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "record_list, 0, 1, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "= [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2,", "4, 3, total_sites=1 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1,", "vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5,", "self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) #", "800 # was included in the last split file, but the use_end_index was", "gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size)", "= {} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in", "record_list, 1, 16, total_sites=1 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1,", "), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), )", "(0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), ) self.assertEqual( (0, 1,", "record_list, 0, 1, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5,", "cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0,", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") )", "cause a minos bug. Last record was not being used # when merging", "variant at 800 # was included in the last split file, but the", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ),", "total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ),", "{} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in split_list]", "record_list, 5, 5, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), ) self.assertEqual(", ") self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=4 ), ) self.assertEqual(", ") self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), ) self.assertEqual(", "self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1 ), ) self.assertEqual( (0,", "0, 2, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "record_list, 0, 4, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "1, 16, total_sites=1 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1,", ") self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), ) self.assertEqual(", "1, total_alleles=3 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4", "1, total_sites=2 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3", "minos error because variant at 800 # was included in the last split", "vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records =", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4, vcf5, vcf6], got_records) got_header, got_records =", "1, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15,", "self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self): \"\"\"test make_split_files with different", "1, total_alleles=9 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10", "So the one at 800 was not getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"),", "3, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5", "= cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 =", "records cause a minos bug. Last record was not being used # when", "split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\"", "1, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), ) self.assertEqual( (0,", "1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), ) self.assertEqual( (0, 1, 4),", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") # These records caused minos error because variant at 800 # was", "total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ),", "merging because the index was wrong. # They are test data from multi_sample_pipeline", "self.ALT = alt test_dict = { \"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")],", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5, 7, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17,", "0, 4, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", "(2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), ) self.assertEqual( (1, 5,", "self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 3, total_sites=1 ), ) self.assertEqual( (0,", "vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines,", "(4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), ) self.assertEqual( (3, 5,", "(0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), ) self.assertEqual( (0, 2,", "0, 1, total_alleles=1 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "# was included in the last split file, but the use_end_index was at", "cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t18\\t.\\tA\\tG\\t.\\tPASS\\t.\\t.\\t.\" )", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), ) self.assertEqual( (0, 0,", "variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") )", "self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta,", ") self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), ) self.assertEqual(", "ref_fasta=ref_fa, variants_per_split=2, flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\")", "1, total_sites=6 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1", ") self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), ) self.assertEqual(", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=8 ), ) self.assertEqual( (0,", "got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\"", "record_list, 0, 1, total_alleles=3 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), ) self.assertEqual( (0,", "total_alleles=12 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ),", "), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=3 ), )", "record_list, 4, 3, total_sites=1 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4,", "gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4,", "ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1,", "total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ),", "vcf6 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t21\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf7 = cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [", "5, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2,", "2, 100, total_sites=2 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100,", "\"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) vcf5", "= os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4,", "record_list, 0, 4, total_sites=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1,", "4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), ) self.assertEqual( (0, 5, 5),", "flank_length=1, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), ) self.assertEqual( (0, 1,", "\"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 =", ") self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), ) self.assertEqual(", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), ) self.assertEqual(", "610. So the one at 800 was not getting used. record_list = [", "1, total_alleles=5 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "got_header) self.assertEqual([vcf1, vcf2, vcf3], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines,", "getting used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0,", "tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out,", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2 ),", "total_alleles=11 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ),", "\"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" )", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=8 ), )", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=1 ), ) self.assertEqual( (0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), ) self.assertEqual( (3, 5, 5),", "4, 100, total_sites=2 ), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\")", "\"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out,", "\"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records =", "), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 100, total_sites=2 ), )", "= 24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def", "\"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits)", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), )", "\"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5,", ") self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=2 ), ) self.assertEqual(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir,", "0, 3, total_sites=8 ), ) self.assertEqual( (0, 0, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", "this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test", "self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), ) self.assertEqual( (0,", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), ) self.assertEqual( (0, 1,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), ) self.assertEqual( (0, 0,", "record_list, 0, 1, total_alleles=2 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "3, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=7", ") self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), ) self.assertEqual(", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), ) self.assertEqual( (0,", "(0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), ) self.assertEqual( (0, 4,", "), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), )", "got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\")", "when merging because the index was wrong. # They are test data from", "total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ),", "), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), )", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=1 ), ) self.assertEqual(", "cluster_vcf_records.vcf_record.VcfRecord( \"ref2\\t42\\t.\\tC\\tG\\t.\\tPASS\\t.\\t.\\t.\" ) header_lines = [ \"##header1\", \"##header2\", \"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tsample_name\", ] chunker = vcf_chunker.VcfChunker(", "chunker.make_split_files() to_merge = {} for ref, split_list in chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100, total_sites=2", "record_list, 0, 1, total_alleles=12 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", ") self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), ) self.assertEqual(", "Test with two threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2,", "from previous test\"\"\" # These records cause a minos bug. Last record was", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=7 ), )", "They are test data from multi_sample_pipeline tests infile = os.path.join(data_dir, \"make_split_files2.in.vcf\") tmp_out =", "to_merge[ref] = [x.filename for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge, tmp_vcf_out) self.assertTrue(filecmp.cmp(vcf_to_split,", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=7 ), )", "), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), )", ") self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), ) self.assertEqual(", "self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=12 ), ) self.assertEqual( (0,", "got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header)", "} expect_variants = 5 expect_alleles = 24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict)", "), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), )", "), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), )", "0, 1, total_alleles=11 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", ") self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), ) self.assertEqual(", "= [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200,", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "used. record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t75\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), ) self.assertEqual( (0, 0, 2),", "record_list, 0, 4, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "# These records cause a minos bug. Last record was not being used", "(5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), ) self.assertEqual( (5, 5,", "vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5)", "chunker.vcf_split_files.items(): to_merge[ref] = [x.filename for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge, tmp_vcf_out)", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "record_list, 0, 3, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3, vcf4,", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), ) self.assertEqual( (0, 5,", "the index was wrong. # They are test data from multi_sample_pipeline tests infile", "import cluster_vcf_records from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\",", "\"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=5 ), )", "record_list, 4, 2, total_sites=1 ), ) self.assertEqual( (3, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4,", "total_sites=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ),", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=1 ), ) self.assertEqual( (0, 1, 2),", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), )", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "17, total_sites=2 ), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2", "cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker =", "4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), ) self.assertEqual( (0, 5, 5),", "threads chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files()", "chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self):", "1, total_alleles=4 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5", "def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir", "from minos import vcf_chunker this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class", "vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6],", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), ) self.assertEqual( (0,", "self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 15, total_sites=1 ), ) self.assertEqual( (0,", "1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), ) self.assertEqual( (0, 1, 3),", "self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), ) self.assertEqual( (4,", "chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header,", "total_alleles=8 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ),", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), )", "0, 3, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "= vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2", "\"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split,", "1, total_alleles=8 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9", ") self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3, total_sites=2 ), ) self.assertEqual(", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list(", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4, total_sites=2 ),", "3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "5, 6, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 7,", ") self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") )", "expect_alleles = 24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles)", "os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5)", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "5, 3, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 4,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=1 ), ) self.assertEqual( (5, 5, 5),", "1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2 ), ) self.assertEqual( (0, 2, 3),", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "(0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), ) self.assertEqual( (0, 5,", "record_list, 5, 3, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "), ) def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\"", "record_list, 0, 1, total_alleles=6 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), ) self.assertEqual( (0,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=6 ), ) self.assertEqual(", "self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header)", "(0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=11 ), ) self.assertEqual( (0, 3,", ") self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), ) self.assertEqual(", "total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ),", "got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split)", "), ) self.assertEqual( (1, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 19, total_sites=2 ), )", "tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir, \"make_split_files.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) vcf1 = cluster_vcf_records.vcf_record.VcfRecord(", ") self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=6 ), ) self.assertEqual(", "0, 2, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2,", "= [x.filename for x in split_list] tmp_vcf_out = \"tmp.vcf_chunker.merge_files.out.vcf\" chunker.merge_files(to_merge, tmp_vcf_out) self.assertTrue(filecmp.cmp(vcf_to_split, tmp_vcf_out,", "tmp_out = \"tmp.vcf_chunker.make_split_files2\" ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker(", "100, total_sites=2 ), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2", "vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"),", "(0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=9 ), ) self.assertEqual( (0, 2,", "(3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), ) self.assertEqual( (2, 5,", "\"ref1\\t1\\t.\\tG\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf2 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t2\\t.\\tC\\tT\\t.\\tPASS\\t.\\t.\\t.\" ) vcf3 = cluster_vcf_records.vcf_record.VcfRecord( \"ref1\\t3\\t.\\tT\\tA\\t.\\tPASS\\t.\\t.\\t.\" ) vcf4", "1, total_sites=1 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2", "vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.3.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records)", "total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ),", "test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa = os.path.join(data_dir,", ") self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), ) self.assertEqual(", "0, 1, total_alleles=8 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "4, 1, total_sites=1 ), ) self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2,", "vcf4, vcf5], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.1.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf4,", "ref_fa = os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa,", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=4 ), ) self.assertEqual( (0,", "= vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test", "vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 =", "(3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), ) self.assertEqual( (3, 5,", "record_list, 0, 1, total_alleles=9 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "expect_variants = 5 expect_alleles = 24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants,", "4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=5 ), ) self.assertEqual( (0, 5, 5),", ") self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8 ), ) self.assertEqual(", ") self.assertEqual( (4, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 2, total_sites=1 ), ) self.assertEqual(", ") self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 6, total_sites=2 ), ) self.assertEqual(", "record_list, 0, 100, total_sites=2 ), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2,", ") = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list =", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), ) self.assertEqual( (0,", ") self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), ) self.assertEqual(", "record_list, 0, 1, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), )", "3, total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=2", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 17, total_sites=2 ), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "15, total_sites=1 ), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 16, total_sites=1", "split file, but the use_end_index was at # position of the variant at", "), ) self.assertEqual( (2, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 2, 100, total_sites=2 ), )", "merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker", "record_list, 0, 3, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "\"chrom1\": [FakeVcf(\"123\"), FakeVcf(\"1\"), FakeVcf(\"123456789\")], \"chrom2\": [FakeVcf(\"12\"), FakeVcf(\"1234\")], } expect_variants = 5 expect_alleles =", "self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ), ) self.assertEqual( (1,", "= vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 =", "0, 3, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 20, total_sites=2 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "caused minos error because variant at 800 # was included in the last", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5),", ") self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=1 ), ) self.assertEqual(", "), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ), )", "record_list, 0, 3, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), )", "record_list, 1, 15, total_sites=1 ), ) self.assertEqual( (0, 1, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ), ) self.assertEqual( (5, 5, 5),", "), ) self.assertEqual( (5, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 2, total_sites=2 ), )", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "data_dir = os.path.join(this_dir, \"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf:", "5, 2, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 3,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t150\\t.\\tG\\tA,T\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t450\\t.\\tT\\tC\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t610\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t800\\t.\\tC\\tCA\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 1, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 100,", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), ) self.assertEqual( (0,", "1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=5 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "= os.path.join(data_dir, \"make_split_files2.in.ref.fa\") if os.path.exists(tmp_out): shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2,", "got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test _chunk_end_indexes_from_vcf_record_list\"\"\" record_list = [ cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t1\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\"", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", ") self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=4 ), ) self.assertEqual(", "\"ref\\t2\\t.\\tC\\tT,A,G,TA\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t3\\t.\\tT\\tA,C\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord( \"ref\\t5\\t.\\tAGAGTCACGTA\\tG\\t.\\t.\\t.\\t.\" ), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t18\\t.\\tA\\tG\\t.\\t.\\t.\\t.\"), cluster_vcf_records.vcf_record.VcfRecord(\"ref\\t21\\t.\\tG\\tT\\t.\\t.\\t.\\t.\"), ] self.assertEqual( (0, 0, 1),", "0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=3 ), ) self.assertEqual( (0, 0, 1),", "record_list, 0, 1, total_alleles=10 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "0, 3, total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=2 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 21, total_sites=2 ), ) # These records caused", "0, 3, total_sites=4 ), ) self.assertEqual( (0, 4, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3,", "\"data\", \"vcf_chunker\") class TestVcfChunker(unittest.TestCase): def test_total_variants_and_alleles_in_vcf_dict(self): \"\"\"test _total_variants_and_alleles_in_vcf_dict\"\"\" class FakeVcf: def __init__(self, alt):", ") def test_make_split_files(self): \"\"\"test make_split_files\"\"\" infile = os.path.join(data_dir, \"make_split_files.in.vcf\") tmp_out = \"tmp.vcf_chunker.make_split_files\" ref_fa", "record was not being used # when merging because the index was wrong.", "5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=6 ), ) self.assertEqual( (0, 5, 5),", "3, total_sites=3 ), ) self.assertEqual( (0, 3, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=4", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 1, total_sites=6 ), ) self.assertEqual( (4,", "record_list, 5, 17, total_sites=2 ), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "1, total_alleles=6 ), ) self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=7", "got_header) self.assertEqual([vcf2, vcf3, vcf4], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines,", "os.path.join(tmp_out, \"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf5, vcf6], got_records) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out,", "total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ),", "record_list, 0, 2, total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "minos bug. Last record was not being used # when merging because the", "1, total_sites=6 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7", "self.assertEqual( (0, 1, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 1, 2, total_sites=1 ), ) self.assertEqual( (0,", "record_list, 5, 2, total_sites=2 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "previous test\"\"\" # These records cause a minos bug. Last record was not", "total_sites=2 ), ) self.assertEqual( (2, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 18, total_sites=2 ),", "3, total_sites=7 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=8", "record_list, 0, 1, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0,", "shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\")", "self.assertEqual(3, len(chunker2.vcf_split_files[\"ref.0\"])) self.assertEqual(4, chunker2.vcf_split_files[\"ref.0\"][-1].use_end_index) shutil.rmtree(tmp_out) def test_merge_files(self): \"\"\"test merge_files\"\"\" vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\")", "total_sites=1 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 1, total_sites=2 ),", "(0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=1 ), ) self.assertEqual( (0, 0,", "0, 1, total_alleles=5 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1,", "self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=3 ), ) self.assertEqual( (0,", "0, 4, total_sites=5 ), ) self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4,", "= vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length)", "index was wrong. # They are test data from multi_sample_pipeline tests infile =", "chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, threads=2, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle))", "total_sites=2 ), ) self.assertEqual( (0, 2, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 3, total_sites=3 ),", "\"split.2.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.3.in.vcf\"))) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile,", "self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files,", "( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants) self.assertEqual(expect_alleles, got_alleles) def test_chunk_end_indexes_from_vcf_record_list(self): \"\"\"test", "chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2", "= 5 expect_alleles = 24 ( got_variants, got_alleles, ) = vcf_chunker.VcfChunker._total_variants_and_alleles_in_vcf_dict(test_dict) self.assertEqual(expect_variants, got_variants)", "self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=2 ), ) self.assertEqual( (0,", ") chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1,", "self.assertTrue(os.path.exists(chunker.metadata_pickle)) got_header, got_records = cluster_vcf_records.vcf_file_read.vcf_file_to_list( os.path.join(tmp_out, \"split.0.in.vcf\") ) self.assertEqual(header_lines, got_header) self.assertEqual([vcf1, vcf2, vcf3,", "2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_alleles=10 ), ) self.assertEqual( (0, 2, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "was not being used # when merging because the index was wrong. #", "= \"tmp.vcf_chunker.merge_files\" chunker = vcf_chunker.VcfChunker( tmp_outdir, vcf_infile=vcf_to_split, ref_fasta=ref_fasta, variants_per_split=4, flank_length=3, gramtools_kmer_size=5, ) chunker.make_split_files()", "variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(1, len(chunker2.vcf_split_files)) self.assertEqual(3,", "record_list, 5, 7, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5,", "tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=2, flank_length=200, gramtools_kmer_size=5, ) chunker.make_split_files() self.assertTrue(os.path.exists(chunker.metadata_pickle)) chunker2 = vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5)", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=8 ), ) self.assertEqual( (0, 0, 2), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=7 ), ) self.assertEqual( (0,", "self.assertEqual([vcf7], got_records) self.assertFalse(os.path.exists(os.path.join(tmp_out, \"split.4.in.vcf\"))) shutil.rmtree(tmp_out) chunker = vcf_chunker.VcfChunker( tmp_out, vcf_infile=infile, ref_fasta=ref_fa, variants_per_split=4, flank_length=3,", "total_sites=1 ), ) self.assertEqual( (0, 1, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 4, total_sites=2 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 4, 3, total_sites=1 ), ) self.assertEqual( (4, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 5, 5, total_sites=2 ), ) self.assertEqual( (3, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list(", "total_sites=4 ), ) self.assertEqual( (0, 4, 4), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=5 ),", "vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1, total_sites=3 ), ) self.assertEqual( (0, 3, 3), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list,", "vcf_to_split = os.path.join(data_dir, \"merge_files.in.vcf\") ref_fasta = os.path.join(data_dir, \"merge_files.in.ref.fa\") tmp_outdir = \"tmp.vcf_chunker.merge_files\" chunker =", "vcf_chunker.VcfChunker(tmp_out, gramtools_kmer_size=5) self.assertEqual(chunker.vcf_infile, chunker2.vcf_infile) self.assertEqual(chunker.ref_fasta, chunker2.ref_fasta) self.assertEqual(chunker.variants_per_split, chunker2.variants_per_split) self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size,", "self.assertEqual( (0, 5, 5), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 2, total_sites=6 ), ) self.assertEqual( (0,", "self.assertEqual(chunker.total_splits, chunker2.total_splits) self.assertEqual(chunker.flank_length, chunker2.flank_length) self.assertEqual(chunker.gramtools_kmer_size, chunker2.gramtools_kmer_size) self.assertEqual(chunker.total_split_files, chunker2.total_split_files) self.assertEqual(chunker.vcf_split_files, chunker2.vcf_split_files) shutil.rmtree(tmp_out) def test_make_split_files_2(self):", "0, 1, total_alleles=12 ), ) self.assertEqual( (0, 0, 1), vcf_chunker.VcfChunker._chunk_end_indexes_from_vcf_record_list( record_list, 0, 1," ]
[]
[ "folder = Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')): with p.open('r') as", "p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ ==", "in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ == \"__main__\":", "[] for p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if", "pd from pathlib import Path import json def load_results_df(folder='results'): folder = Path(folder) results_dicts", "json def load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')):", "as pd from pathlib import Path import json def load_results_df(folder='results'): folder = Path(folder)", "Path import json def load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for p", "<filename>labs/03_neural_recsys/movielens_paramsearch_results.py import pandas as pd from pathlib import Path import json def load_results_df(folder='results'):", "import json def load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for p in", "def load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')): with", "sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ == \"__main__\": df", "= Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')): with p.open('r') as f:", "import pandas as pd from pathlib import Path import json def load_results_df(folder='results'): folder", "f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ == \"__main__\": df = load_results_df().sort_values(by=['test_mae'], ascending=True) print(df.head(5))", "with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ == \"__main__\": df =", "p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ == \"__main__\": df = load_results_df().sort_values(by=['test_mae'],", "Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f))", "= [] for p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts)", "pathlib import Path import json def load_results_df(folder='results'): folder = Path(folder) results_dicts = []", "as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__ == \"__main__\": df = load_results_df().sort_values(by=['test_mae'], ascending=True)", "import Path import json def load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for", "for p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return pd.DataFrame.from_dict(results_dicts) if __name__", "from pathlib import Path import json def load_results_df(folder='results'): folder = Path(folder) results_dicts =", "load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')): with p.open('r')", "results_dicts = [] for p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts.append(json.load(f)) return", "pandas as pd from pathlib import Path import json def load_results_df(folder='results'): folder =" ]
[ "FastRectDiag import FastRectDiag import profile def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print", "print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)])", "\"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)])", "print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy()", "counter=0 ## diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag", "succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag", "RectDia import RectDia from FastRectDiag import FastRectDiag import profile def printHistory(diag): tmp=diag while(1):", ":print tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor", "diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not an", "## print len(diag.succCa()) for k in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced()", "tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted", "import FastRectDiag from RectDia import RectDia from FastRectDiag import FastRectDiag import profile def", "print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print", "if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if", "if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import profile profile.run(\"print unknot(dd,10000)\")", "stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop()", "## print diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ##", "if len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if", "print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0", "from FastRectDiag import FastRectDiag import profile def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0", "tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print", "diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return", "not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else:", "\"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1])", "break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return", "tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity", "stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag)", "stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print", "## printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw()", "print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not", "counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag)", "stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in succ:", "RectDia from FastRectDiag import FastRectDiag import profile def printHistory(diag): tmp=diag while(1): ## if", "k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ##", "return (\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return", "printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag)", "def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ##", "print len(diag.succCa()) for k in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if", "== \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import profile profile.run(\"print unknot(dd,10000)\") ## print", "continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in succ: ## if not hmap.has_key(k.hashInt()):", "## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted", "print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points)", "<filename>src/KnotTheory/HFK-Zurich/simplify/fastUnknot2.py import RectDia import FastRectDiag from RectDia import RectDia from FastRectDiag import FastRectDiag", "print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag)", "if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if", "tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0:", "diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print", "if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted", "while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!!", "hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__", "diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa())", "unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if", "tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound):", "## print len(diag.points) ## print diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0})", "diag=tmp ## print len(diag.points) ## print diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!!", "print diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print", "hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack", "FastRectDiag import profile def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ##", "hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop() ##", "counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__ ==", "print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print diag.xSorted", "counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\": ##", "__name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import profile profile.run(\"print unknot(dd,10000)\") ##", "## print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound):", "len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3:", "## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print", "tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break", "diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable()", "## printHistory(diag) return (\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ##", "len(diag.succCa()) for k in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0:", "diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print diag.xSorted ##", "(\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted ##", "(\"not an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not", "if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\":", "## diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp", "## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ##", "succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable():", "RectDia import FastRectDiag from RectDia import RectDia from FastRectDiag import FastRectDiag import profile", "## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print", "tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted", "tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print diag.xSorted ## print diag.ySorted", "k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0", "return (\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import profile", "## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice()", "print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k", "if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break", "import profile def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print", "n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag) return (\"not an unknot\",diag) else:", "printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ## print", "## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in succ: ##", "for k in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp)", "print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ## printHistory(diag)", "if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap)))", "## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for", "stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in succ: ## if", "stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if", "diag.draw()##debug!! ## print diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ##", "import RectDia import FastRectDiag from RectDia import RectDia from FastRectDiag import FastRectDiag import", "else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable():", "while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted print", "len(diag.points) ## print diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap)", "def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if", "from RectDia import RectDia from FastRectDiag import FastRectDiag import profile def printHistory(diag): tmp=diag", "wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ##", "unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0:", "tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print diag.xSorted ## print diag.ySorted stack=[diag]", "FastRectDiag from RectDia import RectDia from FastRectDiag import FastRectDiag import profile def printHistory(diag):", "tmp.isdestabilisable() ## print tmp.xSorted ## print tmp.ySorted print tmp.toRectDia().toStringNice() if tmp.predecessor==0:break tmp=tmp.predecessor def", "diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0}) while(counter<bound): if len(stack)==0: ##", "des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print diag.xSorted ## print", "tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1", "profile def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable() ## print tmp.xSorted", "diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in", "return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted", "if tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag]", "tmp.predecessor=diag diag=tmp ## print len(diag.points) ## print diag.xSorted ## print diag.ySorted stack=[diag] ##", "printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print", "(\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import profile profile.run(\"print", "knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!! ## print diag.xSorted ## print", "hmap=dict({diag.hashInt():0}) continue succ=diag.fastsuccCa(hmap) ## print len(diag.succCa()) for k in succ: ## if not", "k in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break", "import RectDia from FastRectDiag import FastRectDiag import profile def printHistory(diag): tmp=diag while(1): ##", "if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ##", "an unknot\",diag) else: diag=stack.pop() ## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag)", "diag.xSorted ## print diag.ySorted des=diag.isdestabilisable() tmp=diag.copy() tmp.m_destabilisation(des[0],des[1]) tmp.predecessor=diag diag=tmp ## print len(diag.points) ##", "in succ: ## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if", "## if not hmap.has_key(k.hashInt()): k.predecessor=diag tmp=k.isdestabilisableAdvanced() if tmp!=0: stack.append(tmp) break if k.isdestabilisable(): stack.append(k)", "print len(diag.points) ## print diag.xSorted ## print diag.ySorted stack=[diag] ## stack[0].draw()##debug!! hmap=dict({diag.hashInt():0}) continue", "import FastRectDiag import profile def printHistory(diag): tmp=diag while(1): ## if tmp.isdestabilisable()!=0 :print tmp.isdestabilisable()", "## diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack))", "printHistory(diag) return (\"unknown\",diag) if __name__ == \"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import", "diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0 ## diag.draw()##debug!!", "diag.draw()##debug!! if diag.complexity<3: ## printHistory(diag) return (\"not knotted\",diag) if diag.isdestabilisable(): print \"reduction!\"+str(len(stack)) counter=0", "else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please wait!\"+str((counter,len(hmap))) ## printHistory(diag) return (\"unknown\",diag)", "\"__main__\": ## dd=RectDia([(0,0),(0,4),(1,2),(1,8),(2,7),(2,9),(3,6),(3,8),(4,1),(4,3),(5,2),(5,7),(6,0),(6,3),(7,1),(7,5),(8,4),(8,6),(9,5),(9,9)]) dd=RectDia([(0,23),(0,6),(1,21),(1,7),(2,19),(2,11),(3,0),(3,4),(4,5),(4,18),(5,3),(5,1),(6,7),(6,2),(7,16),(7,8),(8,11),(8,6),(9,13),(9,5),(10,12),(10,4),(11,9),(11,3),(12,15),(12,8),(13,21),(13,13),(14,10),(14,1),(15,15),(15,9),(16,17),(16,14),(17,16),(17,12),(18,18),(18,10),(19,14),(19,0),(20,20),(20,17),(21,22),(21,19),(22,23),(22,20),(23,22),(23,2)]) ## dd.draw() import profile profile.run(\"print unknot(dd,10000)\") ## print unknot(dd)", "tmp.predecessor==0:break tmp=tmp.predecessor def unknot(diag,bound): diag=FastRectDiag(diag) print diag.xSorted print diag.ySorted counter=0 n=diag.complexity stack=[diag] hmap=dict({diag.hashInt():0})", "break if k.isdestabilisable(): stack.append(k) break else: stack=[k]+stack hmap[k.hashInt()]=0 counter+=1 if counter%5000==0: print \"Please" ]
[ "except Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file +", "if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses returns 100 if not", "= productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path,", "parametro adicional ao comando de build/make \"\"\" fctrl = FrontController() self.__error = False", "2012 Controle do build, extract feito de funções do legado. \"\"\" import legacy.makefile", "self.__log(out) if self.cancel == True or self.__error == True: self.job.close() self.__log(\"Cancelado: \" +", "builder <> None: builder.close() return success def generate_res_file(self, path, file, dataRes): \"\"\" Gera", "elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") == 0 and string.find(linha, \"None\")", "arquivo RES do projeto \"\"\" success = True builder = None try: builder", "foi possivel gerar RES para \" + file) success = False finally: if", "self.__log(\"Cancelado: \" + file) self.cancel = False return 100 self.job = None return", "class Msg: SUCCESS = 0 WARNING = 1 ERROR = 2 EOF =", "3 class Ctrl(object): \"\"\" @author rpereira Classe de controle do build. \"\"\" #Borg", "as futil import wx import string import re from controller.front import FrontController from", "builder.close() return success def generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo RES do", "= False self.cmd = False self.__error = False def set_cmd(self): self.cmd = True", "False return 100 self.job = None return 0 def altera_versao(self, version, path): \"\"\"", "linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret", "import multiprocessing import sys class Msg: SUCCESS = 0 WARNING = 1 ERROR", "RES para \" + file) success = False finally: if builder <> None:", "in listVal: msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR): self.__error =", "return 100 num_threads = fctrl.get_num_threads() try: if num_threads == 0: num_threads = multiprocessing.cpu_count()", "arquivo RES do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes =", "dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject", "Msg.ERROR): self.__error = True print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1)", "\"\": self.__log(\"FIM: \" + file) return self.job.close() self.__log(out) if self.cancel == True or", "return 100 self.job = None return 0 def altera_versao(self, version, path): \"\"\" Edita", "\"None\") != -1)): ret = Msg.WARNING return ret def __log(self, text): \"\"\" Imprime", "path, file, num_threads > 1) self.job.compile(paramExtr) out = \" \" self.__log(\"make \" +", "\" + file + \" atualizado\") #TODO: extract .mak extension self.job = CompilerBuilder(", "re from controller.front import FrontController from legacy.file import BuilderFile import legacy.fileres as fileres", "linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret == Msg.ERROR): color = wx.RED self.__error", "update_res(self, path, file): \"\"\" Edita e gera o arquivo RES do projeto \"\"\"", "self.job.close() self.__log(\"Cancelado: \" + file) self.cancel = False return 100 self.job = None", "num_threads = fctrl.get_num_threads() try: if num_threads == 0: num_threads = multiprocessing.cpu_count() except Exception:", "versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion", "file) return self.job.close() self.__log(out) if self.cancel == True or self.__error == True: self.job.close()", "self.__error = True print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color", "build. \"\"\" #Borg Design Pattern __shared_state = {} def __init__(self): self.__threads_spin = None", "as fileres import legacy.makefile as mkfile import legacy.altver as altver import multiprocessing import", "alterando a versão \"\"\" success = True out = \"\" try: change_version =", "== 0 and string.find(linha, \"None\") != -1)): ret = Msg.WARNING return ret def", "while True: out = self.job.readMsg() if out == \"\": self.__log(\"FIM: \" + file)", "= False raise e return success def update_res(self, path, file): \"\"\" Edita e", "= fctrl.get_num_threads() try: if num_threads == 0: num_threads = multiprocessing.cpu_count() except Exception: num_threads", "rpereira Apr 10, 2012 Controle do build, extract feito de funções do legado.", "fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel gerar RES", "dataRes) except: self.__log(\"Nao foi possivel gerar RES para \" + file) success =", "(string.find(linha, \"Warning messages:\") == 0 and string.find(linha, \"None\") != -1)): ret = Msg.WARNING", "+ file) #TODO: tirar o while true while True: out = self.job.readMsg() if", "import BuilderFile import legacy.fileres as fileres import legacy.makefile as mkfile import legacy.altver as", "2 EOF = 3 class Ctrl(object): \"\"\" @author rpereira Classe de controle do", "\"None\") != -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\")", "ret = Msg.WARNING return ret def __log(self, text): \"\"\" Imprime texto, na saída", "= None try: builder = BuilderFile(path + \"\\\\\" + file) builder.open() versao =", "BPK/BPR alterando a versão \"\"\" success = True out = \"\" try: change_version", "fctrl = FrontController() self.__error = False #TODO: tirar esses returns 100 (mudar para", "o BPK/BPR alterando a versão \"\"\" success = True out = \"\" try:", "fctrl.get_num_threads() try: if num_threads == 0: num_threads = multiprocessing.cpu_count() except Exception: num_threads =", "= multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" +", "\" atualizado\") #TODO: extract .mak extension self.job = CompilerBuilder( path, file, num_threads >", "def generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo RES do projeto \"\"\" compRes", "finally: if builder <> None: builder.close() return success def generate_res_file(self, path, file, dataRes):", "self.job = None return 0 def altera_versao(self, version, path): \"\"\" Edita o BPK/BPR", "\" + file) self.cancel = False return 100 self.job = None return 0", "Classe de controle do build. \"\"\" #Borg Design Pattern __shared_state = {} def", "\"\"\" success = True builder = None try: builder = BuilderFile(path + \"\\\\\"", "{} def __init__(self): self.__threads_spin = None self.__console_panel = None self.__list_ctrl = None self.__dict__", "do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res')", "100 #TODO: tirar esses returns 100 if not self.update_res(path, file): return 100 num_threads", "linha in listVal: msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR): self.__error", "atualizado\") #TODO: extract .mak extension self.job = CompilerBuilder( path, file, num_threads > 1)", "file + \" atualizado\") #TODO: extract .mak extension self.job = CompilerBuilder( path, file,", "\"\"\" Edita o BPK/BPR alterando a versão \"\"\" success = True out =", "def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path, file,", "= change_version.run() self.__log(out) except Exception as e: print e success = False raise", "#TODO: extract .mak extension self.job = CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr)", "esses returns 100 (mudar para uma mensagem de erro) if not self.altera_versao(fctrl.get_version(), path):", "CompilerBuilder import legacy.futil as futil import wx import string import re from controller.front", "0 WARNING = 1 ERROR = 2 EOF = 3 class Ctrl(object): \"\"\"", "EOF = 3 class Ctrl(object): \"\"\" @author rpereira Classe de controle do build.", "\"Warning messages:\") == 0 and string.find(linha, \"None\") != -1)): ret = Msg.WARNING return", "dado a ser impresso \"\"\" listVal = futil.trata_texto(text) for linha in listVal: msg_ret", "1) self.job.compile(paramExtr) out = \" \" self.__log(\"make \" + file) #TODO: tirar o", "= True print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color =", "== 0: num_threads = multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads)", "do build, extract feito de funções do legado. \"\"\" import legacy.makefile as mkfile", "False raise e return success def update_res(self, path, file): \"\"\" Edita e gera", "RES do projeto \"\"\" success = True builder = None try: builder =", "False finally: if builder <> None: builder.close() return success def generate_res_file(self, path, file,", "= False self.__error = False def set_cmd(self): self.cmd = True def set_console_panel(self, console_panel):", "linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\",", "and string.find(linha, \"None\") != -1)): ret = Msg.WARNING return ret def __log(self, text):", "index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret == Msg.ERROR):", "fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes)", "do build. \"\"\" #Borg Design Pattern __shared_state = {} def __init__(self): self.__threads_spin =", "dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes + \" gerado\")", "file, dataRes) except: self.__log(\"Nao foi possivel gerar RES para \" + file) success", "num_threads = multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \"", "e: print e success = False raise e return success def update_res(self, path,", "file) success = False finally: if builder <> None: builder.close() return success def", "!= -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") !=", "legado. \"\"\" import legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil as", "not (string.find(linha, \"None\") != -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not", "builder = None try: builder = BuilderFile(path + \"\\\\\" + file) builder.open() versao", "messages:\") == 0 and string.find(linha, \"None\") != -1)): ret = Msg.WARNING return ret", "== True or self.__error == True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel =", "wx import string import re from controller.front import FrontController from legacy.file import BuilderFile", "((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") == 0 and", "linha)and not (string.find(linha, \"Warning messages:\") == 0 and string.find(linha, \"None\") != -1)): ret", "\" \" self.__log(\"make \" + file) #TODO: tirar o while true while True:", "self.cmd: if (msg_ret == Msg.ERROR): self.__error = True print linha else: index =", "futil.trata_texto(text) for linha in listVal: msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret ==", "= True elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF):", "altera_versao(self, version, path): \"\"\" Edita o BPK/BPR alterando a versão \"\"\" success =", "== Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color = wx.GREEN self.__list_ctrl.SetItemBackgroundColour(index,", "= self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR): self.__error = True print linha", "if builder <> None: builder.close() return success def generate_res_file(self, path, file, dataRes): \"\"\"", "import legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil as futil import", "legacy.makefile as mkfile import legacy.altver as altver import multiprocessing import sys class Msg:", "None: builder.close() return success def generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo RES", "None self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel = False self.cmd = False", "paramExtr = \"\"): \"\"\" Build/make geral do arquivo de makefile indicado @param path", "if out == \"\": self.__log(\"FIM: \" + file) return self.job.close() self.__log(out) if self.cancel", "False self.cmd = False self.__error = False def set_cmd(self): self.cmd = True def", "file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes =", "returns 100 (mudar para uma mensagem de erro) if not self.altera_versao(fctrl.get_version(), path): return", "== True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel = False return 100 self.job", "def __log(self, text): \"\"\" Imprime texto, na saída definida @param text dado a", "= wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color = wx.GREEN self.__list_ctrl.SetItemBackgroundColour(index, color) self.__list_ctrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)", "fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription", "definida @param text dado a ser impresso \"\"\" listVal = futil.trata_texto(text) for linha", "!= -1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") !=", "fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName =", "self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses returns 100 if not self.update_res(path, file):", "elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif", "def make(self, path, file, paramExtr = \"\"): \"\"\" Build/make geral do arquivo de", "= builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription =", "num_threads) self.__log(\"Makefile: \" + file + \" atualizado\") #TODO: extract .mak extension self.job", "success = True out = \"\" try: change_version = altver.AlteraVer(version, path) out =", "self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path, file, paramExtr = \"\"):", "\"\" try: change_version = altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except Exception as", "do legado. \"\"\" import legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil", "self.job.close() self.__log(out) if self.cancel == True or self.__error == True: self.job.close() self.__log(\"Cancelado: \"", "file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi", "fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes + \" gerado\") def", "__log(self, text): \"\"\" Imprime texto, na saída definida @param text dado a ser", "Controle do build, extract feito de funções do legado. \"\"\" import legacy.makefile as", "string.find(linha, \"None\") != -1)): ret = Msg.WARNING return ret def __log(self, text): \"\"\"", "adicional ao comando de build/make \"\"\" fctrl = FrontController() self.__error = False #TODO:", "return success def generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo RES do projeto", "and not (string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and", "path): return 100 #TODO: tirar esses returns 100 if not self.update_res(path, file): return", "wx.WHITE if (msg_ret == Msg.ERROR): color = wx.RED self.__error = True elif (msg_ret", "False self.__error = False def set_cmd(self): self.cmd = True def set_console_panel(self, console_panel): self.__console_panel", "FrontController() self.__error = False #TODO: tirar esses returns 100 (mudar para uma mensagem", "self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret == Msg.ERROR): color = wx.RED", "def __check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and", "= Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") != -1)): ret =", "if (msg_ret == Msg.ERROR): self.__error = True print linha else: index = self.__list_ctrl.GetItemCount()", "self.cmd = True def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def", "e return success def update_res(self, path, file): \"\"\" Edita e gera o arquivo", "UTF-8 -*- \"\"\" @author rpereira Apr 10, 2012 Controle do build, extract feito", "print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if", "import legacy.makefile as mkfile import legacy.altver as altver import multiprocessing import sys class", "a versão \"\"\" success = True out = \"\" try: change_version = altver.AlteraVer(version,", "-1)): ret = Msg.WARNING return ret def __log(self, text): \"\"\" Imprime texto, na", "mkfile import legacy.altver as altver import multiprocessing import sys class Msg: SUCCESS =", "file, paramExtr = \"\"): \"\"\" Build/make geral do arquivo de makefile indicado @param", "projeto \"\"\" success = True builder = None try: builder = BuilderFile(path +", "\" + file) return self.job.close() self.__log(out) if self.cancel == True or self.__error ==", "+ file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes", "10, 2012 Controle do build, extract feito de funções do legado. \"\"\" import", "compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \"", "(string.find(linha, \"None\") != -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha,", "not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses returns 100 if not self.update_res(path,", "def altera_versao(self, version, path): \"\"\" Edita o BPK/BPR alterando a versão \"\"\" success", "de makefile @param parametro adicional ao comando de build/make \"\"\" fctrl = FrontController()", "path) out = change_version.run() self.__log(out) except Exception as e: print e success =", "self.__error = False def set_cmd(self): self.cmd = True def set_console_panel(self, console_panel): self.__console_panel =", "!= -1)): ret = Msg.WARNING return ret def __log(self, text): \"\"\" Imprime texto,", "impresso \"\"\" listVal = futil.trata_texto(text) for linha in listVal: msg_ret = self.__check_msg(linha) if", "FrontController from legacy.file import BuilderFile import legacy.fileres as fileres import legacy.makefile as mkfile", "import sys class Msg: SUCCESS = 0 WARNING = 1 ERROR = 2", "-1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") != -1)):", "(string.find(linha, \"Error messages:\") == 0 and string.find(linha, \"None\") != -1)): ret = Msg.ERROR", "altver import multiprocessing import sys class Msg: SUCCESS = 0 WARNING = 1", "\" + file) success = False finally: if builder <> None: builder.close() return", "= futil.trata_texto(text) for linha in listVal: msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret", "geral do arquivo de makefile indicado @param path do arquivo de makefile @param", "linha))and not (string.find(linha, \"Error messages:\") == 0 and string.find(linha, \"None\") != -1)): ret", "\"\"\" @author rpereira Apr 10, 2012 Controle do build, extract feito de funções", "import re from controller.front import FrontController from legacy.file import BuilderFile import legacy.fileres as", "legacy.altver as altver import multiprocessing import sys class Msg: SUCCESS = 0 WARNING", "-1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") != -1)):", "= fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject =", "__check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not", "elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.EOF elif", "= versao dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName", "return self.job.close() self.__log(out) if self.cancel == True or self.__error == True: self.job.close() self.__log(\"Cancelado:", "from legacy.compiler_builder import CompilerBuilder import legacy.futil as futil import wx import string import", "futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes + \" gerado\") def __check_msg(self, linha):", "msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR): self.__error = True print", "builder = BuilderFile(path + \"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription =", "= Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\")", "= wx.WHITE if (msg_ret == Msg.ERROR): color = wx.RED self.__error = True elif", "= None self.__console_panel = None self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel =", "fileRes + \" gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha)", "generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo RES do projeto \"\"\" compRes =", "False #TODO: tirar esses returns 100 (mudar para uma mensagem de erro) if", ".mak extension self.job = CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr) out =", "ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") != -1)): ret", "ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") != -1)): ret", "100 num_threads = fctrl.get_num_threads() try: if num_threads == 0: num_threads = multiprocessing.cpu_count() except", "success = False finally: if builder <> None: builder.close() return success def generate_res_file(self,", "not (string.find(linha, \"Warning messages:\") == 0 and string.find(linha, \"None\") != -1)): ret =", "def update_res(self, path, file): \"\"\" Edita e gera o arquivo RES do projeto", "self.cancel == True or self.__error == True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel", "fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes", "\"None\") != -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning", "tirar o while true while True: out = self.job.readMsg() if out == \"\":", "= False #TODO: tirar esses returns 100 (mudar para uma mensagem de erro)", "dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file)", "self.cancel = False self.cmd = False self.__error = False def set_cmd(self): self.cmd =", "except Exception as e: print e success = False raise e return success", "out = self.job.readMsg() if out == \"\": self.__log(\"FIM: \" + file) return self.job.close()", "self.__threads_spin = None self.__console_panel = None self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel", "self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR): self.__error = True print linha else:", "\"\"): \"\"\" Build/make geral do arquivo de makefile indicado @param path do arquivo", "None try: builder = BuilderFile(path + \"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\")", "0: num_threads = multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile:", "success = True builder = None try: builder = BuilderFile(path + \"\\\\\" +", "as e: print e success = False raise e return success def update_res(self,", "= 2 EOF = 3 class Ctrl(object): \"\"\" @author rpereira Classe de controle", "'res') self.__log(\"Arquivo RES: \" + fileRes + \" gerado\") def __check_msg(self, linha): ret", "path, file): \"\"\" Edita e gera o arquivo RES do projeto \"\"\" success", "return success def update_res(self, path, file): \"\"\" Edita e gera o arquivo RES", "(string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha,", "= 0 WARNING = 1 ERROR = 2 EOF = 3 class Ctrl(object):", "\"\"\" listVal = futil.trata_texto(text) for linha in listVal: msg_ret = self.__check_msg(linha) if self.cmd:", "version, path): \"\"\" Edita o BPK/BPR alterando a versão \"\"\" success = True", "productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file,", "self.__log(\"Nao foi possivel gerar RES para \" + file) success = False finally:", "text): \"\"\" Imprime texto, na saída definida @param text dado a ser impresso", "(msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color = wx.GREEN", "+ fileRes + \" gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\",", "tirar esses returns 100 (mudar para uma mensagem de erro) if not self.altera_versao(fctrl.get_version(),", "versao dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName =", "file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes + \"", "+ \" gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or", "ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error", "Pattern __shared_state = {} def __init__(self): self.__threads_spin = None self.__console_panel = None self.__list_ctrl", "file): \"\"\" Edita e gera o arquivo RES do projeto \"\"\" success =", "Msg.WARNING return ret def __log(self, text): \"\"\" Imprime texto, na saída definida @param", "= self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret == Msg.ERROR): color", "controller.front import FrontController from legacy.file import BuilderFile import legacy.fileres as fileres import legacy.makefile", "\" gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror", "builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName = productName", "= console_panel.list_ctrl def make(self, path, file, paramExtr = \"\"): \"\"\" Build/make geral do", "\"\"\" Gera arquivo RES do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes)", "legacy.futil as futil import wx import string import re from controller.front import FrontController", "mensagem de erro) if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses returns", "if (msg_ret == Msg.ERROR): color = wx.RED self.__error = True elif (msg_ret ==", "texto, na saída definida @param text dado a ser impresso \"\"\" listVal =", "path do arquivo de makefile @param parametro adicional ao comando de build/make \"\"\"", "BuilderFile import legacy.fileres as fileres import legacy.makefile as mkfile import legacy.altver as altver", "dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel", "0 and string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and", "@author rpereira Apr 10, 2012 Controle do build, extract feito de funções do", "out == \"\": self.__log(\"FIM: \" + file) return self.job.close() self.__log(out) if self.cancel ==", "import string import re from controller.front import FrontController from legacy.file import BuilderFile import", "self.cmd = False self.__error = False def set_cmd(self): self.cmd = True def set_console_panel(self,", "= None return 0 def altera_versao(self, version, path): \"\"\" Edita o BPK/BPR alterando", "\"None\") != -1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\")", "#TODO: tirar esses returns 100 if not self.update_res(path, file): return 100 num_threads =", "None self.__console_panel = None self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel = False", "out = \" \" self.__log(\"make \" + file) #TODO: tirar o while true", "\"\"\" success = True out = \"\" try: change_version = altver.AlteraVer(version, path) out", "= BuilderFile(path + \"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\")", "BuilderFile(path + \"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName", "Apr 10, 2012 Controle do build, extract feito de funções do legado. \"\"\"", "self.__shared_state self.cancel = False self.cmd = False self.__error = False def set_cmd(self): self.cmd", "ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") == 0", "= futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes + \" gerado\") def __check_msg(self,", "100 (mudar para uma mensagem de erro) if not self.altera_versao(fctrl.get_version(), path): return 100", "= self.__shared_state self.cancel = False self.cmd = False self.__error = False def set_cmd(self):", "futil import wx import string import re from controller.front import FrontController from legacy.file", "True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel = False return 100 self.job =", "= False def set_cmd(self): self.cmd = True def set_console_panel(self, console_panel): self.__console_panel = console_panel", "self.__list_ctrl = console_panel.list_ctrl def make(self, path, file, paramExtr = \"\"): \"\"\" Build/make geral", "Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.ERROR", "= builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion =", "self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret == Msg.ERROR): color =", "# -*- coding: UTF-8 -*- \"\"\" @author rpereira Apr 10, 2012 Controle do", "self.__log(out) except Exception as e: print e success = False raise e return", "(msg_ret == Msg.ERROR): color = wx.RED self.__error = True elif (msg_ret == Msg.WARNING):", "= \" \" self.__log(\"make \" + file) #TODO: tirar o while true while", "= Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") == 0 and", "\" + fileRes + \" gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS if", "extension self.job = CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr) out = \"", "\"\"\" #Borg Design Pattern __shared_state = {} def __init__(self): self.__threads_spin = None self.__console_panel", "extract .mak extension self.job = CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr) out", "WARNING = 1 ERROR = 2 EOF = 3 class Ctrl(object): \"\"\" @author", "\" self.__log(\"make \" + file) #TODO: tirar o while true while True: out", "= \"\"): \"\"\" Build/make geral do arquivo de makefile indicado @param path do", "<> None: builder.close() return success def generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo", "Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file + \"", "uma mensagem de erro) if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses", "color = wx.RED self.__error = True elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\")", "import legacy.futil as futil import wx import string import re from controller.front import", "and string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not", "de makefile indicado @param path do arquivo de makefile @param parametro adicional ao", "fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel gerar RES para \" +", "and not (string.find(linha, \"None\") != -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and", "listVal = futil.trata_texto(text) for linha in listVal: msg_ret = self.__check_msg(linha) if self.cmd: if", "console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path, file, paramExtr = \"\"): \"\"\" Build/make", "listVal: msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR): self.__error = True", "multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file", "@author rpereira Classe de controle do build. \"\"\" #Borg Design Pattern __shared_state =", "possivel gerar RES para \" + file) success = False finally: if builder", "= 3 class Ctrl(object): \"\"\" @author rpereira Classe de controle do build. \"\"\"", "= True out = \"\" try: change_version = altver.AlteraVer(version, path) out = change_version.run()", "return 100 #TODO: tirar esses returns 100 if not self.update_res(path, file): return 100", "Msg.ERROR): color = wx.RED self.__error = True elif (msg_ret == Msg.WARNING): color =", "__init__(self): self.__threads_spin = None self.__console_panel = None self.__list_ctrl = None self.__dict__ = self.__shared_state", "or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") == 0 and string.find(linha, \"None\")", "change_version.run() self.__log(out) except Exception as e: print e success = False raise e", "True elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color", "for linha in listVal: msg_ret = self.__check_msg(linha) if self.cmd: if (msg_ret == Msg.ERROR):", "gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\",", "set_cmd(self): self.cmd = True def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl", "self.__log(\"make \" + file) #TODO: tirar o while true while True: out =", "if self.cmd: if (msg_ret == Msg.ERROR): self.__error = True print linha else: index", "if not self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads() try: if num_threads ==", "projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo", "raise e return success def update_res(self, path, file): \"\"\" Edita e gera o", "= fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel gerar RES para \"", "dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject", "funções do legado. \"\"\" import legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder import", "from legacy.file import BuilderFile import legacy.fileres as fileres import legacy.makefile as mkfile import", "de controle do build. \"\"\" #Borg Design Pattern __shared_state = {} def __init__(self):", "do arquivo de makefile indicado @param path do arquivo de makefile @param parametro", "self.job = CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr) out = \" \"", "= Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") != -1)): ret =", "file, num_threads) self.__log(\"Makefile: \" + file + \" atualizado\") #TODO: extract .mak extension", "build/make \"\"\" fctrl = FrontController() self.__error = False #TODO: tirar esses returns 100", "return ret def __log(self, text): \"\"\" Imprime texto, na saída definida @param text", "na saída definida @param text dado a ser impresso \"\"\" listVal = futil.trata_texto(text)", "100 self.job = None return 0 def altera_versao(self, version, path): \"\"\" Edita o", "\"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\")", "de build/make \"\"\" fctrl = FrontController() self.__error = False #TODO: tirar esses returns", "e gera o arquivo RES do projeto \"\"\" success = True builder =", "string import re from controller.front import FrontController from legacy.file import BuilderFile import legacy.fileres", "#TODO: tirar o while true while True: out = self.job.readMsg() if out ==", "ret def __log(self, text): \"\"\" Imprime texto, na saída definida @param text dado", "wx.RED self.__error = True elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret", "file, num_threads > 1) self.job.compile(paramExtr) out = \" \" self.__log(\"make \" + file)", "\"\"\" Edita e gera o arquivo RES do projeto \"\"\" success = True", "self.job.readMsg() if out == \"\": self.__log(\"FIM: \" + file) return self.job.close() self.__log(out) if", "= Msg.WARNING return ret def __log(self, text): \"\"\" Imprime texto, na saída definida", "= True def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def make(self,", "multiprocessing import sys class Msg: SUCCESS = 0 WARNING = 1 ERROR =", "None return 0 def altera_versao(self, version, path): \"\"\" Edita o BPK/BPR alterando a", "linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha)", "try: change_version = altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except Exception as e:", "RES: \" + fileRes + \" gerado\") def __check_msg(self, linha): ret = Msg.SUCCESS", "or self.__error == True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel = False return", "self.__log(\"Makefile: \" + file + \" atualizado\") #TODO: extract .mak extension self.job =", "(msg_ret == Msg.ERROR): self.__error = True print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index,", "True: out = self.job.readMsg() if out == \"\": self.__log(\"FIM: \" + file) return", "de funções do legado. \"\"\" import legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder", "mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil as futil import wx import string", "linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") == 0 and string.find(linha,", "import FrontController from legacy.file import BuilderFile import legacy.fileres as fileres import legacy.makefile as", "= fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel gerar", "Build/make geral do arquivo de makefile indicado @param path do arquivo de makefile", "self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads() try: if num_threads == 0: num_threads", "+ file) self.cancel = False return 100 self.job = None return 0 def", "SUCCESS = 0 WARNING = 1 ERROR = 2 EOF = 3 class", "True def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path,", "if num_threads == 0: num_threads = multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path,", "gerar RES para \" + file) success = False finally: if builder <>", "color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color = wx.GREEN self.__list_ctrl.SetItemBackgroundColour(index, color) self.__list_ctrl.SetColumnWidth(0,", "False def set_cmd(self): self.cmd = True def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl", "#TODO: tirar esses returns 100 (mudar para uma mensagem de erro) if not", "= self.job.readMsg() if out == \"\": self.__log(\"FIM: \" + file) return self.job.close() self.__log(out)", "linha): ret = Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha,", "o arquivo RES do projeto \"\"\" success = True builder = None try:", "= CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr) out = \" \" self.__log(\"make", "returns 100 if not self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads() try: if", "self.__error = False #TODO: tirar esses returns 100 (mudar para uma mensagem de", "success def update_res(self, path, file): \"\"\" Edita e gera o arquivo RES do", "o while true while True: out = self.job.readMsg() if out == \"\": self.__log(\"FIM:", "Exception as e: print e success = False raise e return success def", "@param path do arquivo de makefile @param parametro adicional ao comando de build/make", "num_threads == 0: num_threads = multiprocessing.cpu_count() except Exception: num_threads = 1 mkfile.gera_make(path, file,", "import wx import string import re from controller.front import FrontController from legacy.file import", "(mudar para uma mensagem de erro) if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO:", "file): return 100 num_threads = fctrl.get_num_threads() try: if num_threads == 0: num_threads =", "tirar esses returns 100 if not self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads()", "= altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except Exception as e: print e", "self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel gerar RES para \" + file)", "1 ERROR = 2 EOF = 3 class Ctrl(object): \"\"\" @author rpereira Classe", "True or self.__error == True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel = False", "= False return 100 self.job = None return 0 def altera_versao(self, version, path):", "+ file) return self.job.close() self.__log(out) if self.cancel == True or self.__error == True:", "\"\"\" import legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil as futil", "RES do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file,", "\"\"\" fctrl = FrontController() self.__error = False #TODO: tirar esses returns 100 (mudar", "self.job.compile(paramExtr) out = \" \" self.__log(\"make \" + file) #TODO: tirar o while", "== Msg.ERROR): self.__error = True print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha)", "saída definida @param text dado a ser impresso \"\"\" listVal = futil.trata_texto(text) for", "= FrontController() self.__error = False #TODO: tirar esses returns 100 (mudar para uma", "-1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") ==", "= mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except:", "== 0 and string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha)", "ERROR = 2 EOF = 3 class Ctrl(object): \"\"\" @author rpereira Classe de", "esses returns 100 if not self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads() try:", "> 1) self.job.compile(paramExtr) out = \" \" self.__log(\"make \" + file) #TODO: tirar", "dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao foi possivel gerar RES para", "\"Error messages:\") == 0 and string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif", "do arquivo de makefile @param parametro adicional ao comando de build/make \"\"\" fctrl", "except: self.__log(\"Nao foi possivel gerar RES para \" + file) success = False", "while true while True: out = self.job.readMsg() if out == \"\": self.__log(\"FIM: \"", "messages:\") == 0 and string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\",", "out = \"\" try: change_version = altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except", "arquivo de makefile @param parametro adicional ao comando de build/make \"\"\" fctrl =", "-*- coding: UTF-8 -*- \"\"\" @author rpereira Apr 10, 2012 Controle do build,", "feito de funções do legado. \"\"\" import legacy.makefile as mkfile from legacy.compiler_builder import", "ao comando de build/make \"\"\" fctrl = FrontController() self.__error = False #TODO: tirar", "self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel = False self.cmd = False self.__error", "self.__dict__ = self.__shared_state self.cancel = False self.cmd = False self.__error = False def", "@param text dado a ser impresso \"\"\" listVal = futil.trata_texto(text) for linha in", "mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName = fileProject self.generate_res_file(path, file, dataRes) except: self.__log(\"Nao", "mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file + \" atualizado\") #TODO: extract .mak", "gera o arquivo RES do projeto \"\"\" success = True builder = None", "if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") == 0", "#Borg Design Pattern __shared_state = {} def __init__(self): self.__threads_spin = None self.__console_panel =", "def __init__(self): self.__threads_spin = None self.__console_panel = None self.__list_ctrl = None self.__dict__ =", "+ \" atualizado\") #TODO: extract .mak extension self.job = CompilerBuilder( path, file, num_threads", "\" + file) #TODO: tirar o while true while True: out = self.job.readMsg()", "make(self, path, file, paramExtr = \"\"): \"\"\" Build/make geral do arquivo de makefile", "fileres import legacy.makefile as mkfile import legacy.altver as altver import multiprocessing import sys", "(re.match(\"[F|f]atal\", linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"FIM:\",", "path, file, paramExtr = \"\"): \"\"\" Build/make geral do arquivo de makefile indicado", "controle do build. \"\"\" #Borg Design Pattern __shared_state = {} def __init__(self): self.__threads_spin", "file) self.cancel = False return 100 self.job = None return 0 def altera_versao(self,", "Msg.SUCCESS if ((re.match(\"[E|e]rror\", linha) or re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") ==", "erro) if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses returns 100 if", "[E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") == 0 and string.find(linha, \"None\") != -1)):", "import CompilerBuilder import legacy.futil as futil import wx import string import re from", "path, file, dataRes): \"\"\" Gera arquivo RES do projeto \"\"\" compRes = fileres.FileRes()", "dataRes): \"\"\" Gera arquivo RES do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file,", "Msg: SUCCESS = 0 WARNING = 1 ERROR = 2 EOF = 3", "console_panel.list_ctrl def make(self, path, file, paramExtr = \"\"): \"\"\" Build/make geral do arquivo", "= None self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel = False self.cmd =", "self.__console_panel = None self.__list_ctrl = None self.__dict__ = self.__shared_state self.cancel = False self.cmd", "self.cancel = False return 100 self.job = None return 0 def altera_versao(self, version,", "change_version = altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except Exception as e: print", "file, dataRes): \"\"\" Gera arquivo RES do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path,", "a ser impresso \"\"\" listVal = futil.trata_texto(text) for linha in listVal: msg_ret =", "not self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads() try: if num_threads == 0:", "= \"\" try: change_version = altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except Exception", "= {} def __init__(self): self.__threads_spin = None self.__console_panel = None self.__list_ctrl = None", "= 1 ERROR = 2 EOF = 3 class Ctrl(object): \"\"\" @author rpereira", "def set_cmd(self): self.cmd = True def set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl =", "path): \"\"\" Edita o BPK/BPR alterando a versão \"\"\" success = True out", "= False finally: if builder <> None: builder.close() return success def generate_res_file(self, path,", "color = wx.WHITE if (msg_ret == Msg.ERROR): color = wx.RED self.__error = True", "= fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" +", "import legacy.altver as altver import multiprocessing import sys class Msg: SUCCESS = 0", "makefile indicado @param path do arquivo de makefile @param parametro adicional ao comando", "console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path, file, paramExtr =", "fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path,", "= fileDescription dataRes.productName = productName fileProject = mkfile.find_type_project_bin(path, file) dataRes.internalName = fileProject dataRes.originalFileName", "legacy.compiler_builder import CompilerBuilder import legacy.futil as futil import wx import string import re", "self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret == Msg.ERROR): color = wx.RED self.__error =", "0 and string.find(linha, \"None\") != -1)): ret = Msg.WARNING return ret def __log(self,", "-*- \"\"\" @author rpereira Apr 10, 2012 Controle do build, extract feito de", "(re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") == 0 and string.find(linha, \"None\") !=", "not (string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"FIM:\", linha) and not", "productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName", "True print linha else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE", "= console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path, file, paramExtr = \"\"): \"\"\"", "coding: UTF-8 -*- \"\"\" @author rpereira Apr 10, 2012 Controle do build, extract", "= builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName =", "dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription dataRes.productName = productName fileProject", "string.find(linha, \"None\") != -1)): ret = Msg.ERROR elif (re.match(\"[F|f]atal\", linha) and not (string.find(linha,", "(re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning", "self.__error == True: self.job.close() self.__log(\"Cancelado: \" + file) self.cancel = False return 100", "Gera arquivo RES do projeto \"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes", "@param parametro adicional ao comando de build/make \"\"\" fctrl = FrontController() self.__error =", "1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file + \" atualizado\") #TODO: extract", "re.match(\".*[E|e]rror [E]\\d\\d\\d\\d\", linha))and not (string.find(linha, \"Error messages:\") == 0 and string.find(linha, \"None\") !=", "build, extract feito de funções do legado. \"\"\" import legacy.makefile as mkfile from", "indicado @param path do arquivo de makefile @param parametro adicional ao comando de", "para \" + file) success = False finally: if builder <> None: builder.close()", "makefile @param parametro adicional ao comando de build/make \"\"\" fctrl = FrontController() self.__error", "ser impresso \"\"\" listVal = futil.trata_texto(text) for linha in listVal: msg_ret = self.__check_msg(linha)", "Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color = wx.GREEN self.__list_ctrl.SetItemBackgroundColour(index, color)", "Edita o BPK/BPR alterando a versão \"\"\" success = True out = \"\"", "builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao dataRes.fileDescription = fileDescription", "\"\"\" Build/make geral do arquivo de makefile indicado @param path do arquivo de", "from controller.front import FrontController from legacy.file import BuilderFile import legacy.fileres as fileres import", "try: builder = BuilderFile(path + \"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription", "100 if not self.update_res(path, file): return 100 num_threads = fctrl.get_num_threads() try: if num_threads", "self.__log(\"FIM: \" + file) return self.job.close() self.__log(out) if self.cancel == True or self.__error", "class Ctrl(object): \"\"\" @author rpereira Classe de controle do build. \"\"\" #Borg Design", "text dado a ser impresso \"\"\" listVal = futil.trata_texto(text) for linha in listVal:", "true while True: out = self.job.readMsg() if out == \"\": self.__log(\"FIM: \" +", "return 0 def altera_versao(self, version, path): \"\"\" Edita o BPK/BPR alterando a versão", "Edita e gera o arquivo RES do projeto \"\"\" success = True builder", "True builder = None try: builder = BuilderFile(path + \"\\\\\" + file) builder.open()", "if self.cancel == True or self.__error == True: self.job.close() self.__log(\"Cancelado: \" + file)", "extract feito de funções do legado. \"\"\" import legacy.makefile as mkfile from legacy.compiler_builder", "out = change_version.run() self.__log(out) except Exception as e: print e success = False", "as mkfile import legacy.altver as altver import multiprocessing import sys class Msg: SUCCESS", "+ file + \" atualizado\") #TODO: extract .mak extension self.job = CompilerBuilder( path,", "+ file) success = False finally: if builder <> None: builder.close() return success", "self.__log(\"Arquivo RES: \" + fileRes + \" gerado\") def __check_msg(self, linha): ret =", "arquivo de makefile indicado @param path do arquivo de makefile @param parametro adicional", "CompilerBuilder( path, file, num_threads > 1) self.job.compile(paramExtr) out = \" \" self.__log(\"make \"", "as altver import multiprocessing import sys class Msg: SUCCESS = 0 WARNING =", "True out = \"\" try: change_version = altver.AlteraVer(version, path) out = change_version.run() self.__log(out)", "\"\"\" compRes = fileres.FileRes() compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES:", "sys class Msg: SUCCESS = 0 WARNING = 1 ERROR = 2 EOF", "!= -1)): ret = Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\")", "== \"\": self.__log(\"FIM: \" + file) return self.job.close() self.__log(out) if self.cancel == True", "e success = False raise e return success def update_res(self, path, file): \"\"\"", "== Msg.ERROR): color = wx.RED self.__error = True elif (msg_ret == Msg.WARNING): color", "num_threads > 1) self.job.compile(paramExtr) out = \" \" self.__log(\"make \" + file) #TODO:", "\"\"\" Imprime texto, na saída definida @param text dado a ser impresso \"\"\"", "versão \"\"\" success = True out = \"\" try: change_version = altver.AlteraVer(version, path)", "not (string.find(linha, \"Error messages:\") == 0 and string.find(linha, \"None\") != -1)): ret =", "None self.__dict__ = self.__shared_state self.cancel = False self.cmd = False self.__error = False", "builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes(); dataRes.fileVersion = versao", "= None self.__dict__ = self.__shared_state self.cancel = False self.cmd = False self.__error =", "import legacy.fileres as fileres import legacy.makefile as mkfile import legacy.altver as altver import", "Design Pattern __shared_state = {} def __init__(self): self.__threads_spin = None self.__console_panel = None", "success = False raise e return success def update_res(self, path, file): \"\"\" Edita", "legacy.file import BuilderFile import legacy.fileres as fileres import legacy.makefile as mkfile import legacy.altver", "compRes.CriaRes(path, file, dataRes) fileRes = futil.change_ext(file, 'res') self.__log(\"Arquivo RES: \" + fileRes +", "= wx.RED self.__error = True elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif", "altver.AlteraVer(version, path) out = change_version.run() self.__log(out) except Exception as e: print e success", "self.__error = True elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret ==", "__shared_state = {} def __init__(self): self.__threads_spin = None self.__console_panel = None self.__list_ctrl =", "else: index = self.__list_ctrl.GetItemCount() self.__list_ctrl.InsertStringItem(index, linha) self.__list_ctrl.EnsureVisible(self.__list_ctrl.GetItemCount()-1) color = wx.WHITE if (msg_ret ==", "[W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") == 0 and string.find(linha, \"None\") != -1)):", "Imprime texto, na saída definida @param text dado a ser impresso \"\"\" listVal", "= 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file + \" atualizado\") #TODO:", "de erro) if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar esses returns 100", "builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName = builder.getInfo(\"ProductName\") dataRes = fileres.DataRes();", "set_console_panel(self, console_panel): self.__console_panel = console_panel self.__list_ctrl = console_panel.list_ctrl def make(self, path, file, paramExtr", "num_threads = 1 mkfile.gera_make(path, file, num_threads) self.__log(\"Makefile: \" + file + \" atualizado\")", "\"\"\" @author rpereira Classe de controle do build. \"\"\" #Borg Design Pattern __shared_state", "do projeto \"\"\" success = True builder = None try: builder = BuilderFile(path", "= True builder = None try: builder = BuilderFile(path + \"\\\\\" + file)", "file) #TODO: tirar o while true while True: out = self.job.readMsg() if out", "Ctrl(object): \"\"\" @author rpereira Classe de controle do build. \"\"\" #Borg Design Pattern", "comando de build/make \"\"\" fctrl = FrontController() self.__error = False #TODO: tirar esses", "0 def altera_versao(self, version, path): \"\"\" Edita o BPK/BPR alterando a versão \"\"\"", "success def generate_res_file(self, path, file, dataRes): \"\"\" Gera arquivo RES do projeto \"\"\"", "legacy.makefile as mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil as futil import wx", "+ \"\\\\\" + file) builder.open() versao = builder.getInfo(\"FileVersion\") fileDescription = builder.getInfo(\"FileDescription\") productName =", "legacy.fileres as fileres import legacy.makefile as mkfile import legacy.altver as altver import multiprocessing", "Msg.ERROR elif (re.match(\"FIM:\", linha) and not (string.find(linha, \"None\") != -1)): ret = Msg.EOF", "print e success = False raise e return success def update_res(self, path, file):", "para uma mensagem de erro) if not self.altera_versao(fctrl.get_version(), path): return 100 #TODO: tirar", "Msg.EOF elif (re.match(\".*[W|w]arning [W]\\d\\d\\d\\d\", linha)and not (string.find(linha, \"Warning messages:\") == 0 and string.find(linha,", "rpereira Classe de controle do build. \"\"\" #Borg Design Pattern __shared_state = {}", "elif (msg_ret == Msg.WARNING): color = wx.NamedColour(\"yellow\") elif (msg_ret == Msg.EOF): color =", "as mkfile from legacy.compiler_builder import CompilerBuilder import legacy.futil as futil import wx import", "try: if num_threads == 0: num_threads = multiprocessing.cpu_count() except Exception: num_threads = 1" ]
[ "\"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC", "type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script>", "<script type='text/javascript'> console.log('loaded JS9 partner plugin') </script> # <script type='text/javascript' src='/static/js9colormaps.js'></script>\\ # \"\"\"),)", "= inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception", "<script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 1') </script> # <script", "with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc:", "error message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final", "= JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self, message=None): self.message = message def", "type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 1') </script> # <script type='text/javascript'", "\"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp:", "\"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR =", "os, os.path, traceback from iglesia.utils import message, error # init JS9 configuration #", "JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR):", "f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" #", "when Javascript is not available yet. Determines paths and starts helper processs\"\"\" global", "radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9 code", "exc.message: JS9_ERROR = exc.message # on error, init code replaced by error message", "import Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link", "f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS =", "global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install", "iglesia.utils import message, error # init JS9 configuration # js9 source directory DIRNAME", "{JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization, when Javascript can be injected\"\"\" #", "href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link", "<script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components')", "URL used to access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used", "<gh_stars>1-10 import os, os.path, traceback from iglesia.utils import message, error # init JS9", "import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global", "= iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR}", "f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL", "<link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'>", "init error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization, when Javascript can be", "file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self,", "src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded", "= iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\")", "global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to", "iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using", "traceback.print_exc() JS9_ERROR = \"Error reading init templates: {}\".format(str(exc)) except JS9Error as exc: if", "as exc: traceback.print_exc() JS9_ERROR = \"Error reading init templates: {}\".format(str(exc)) except JS9Error as", "JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except", "# load templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC", "type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script>", "type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components') </script>", "Exception as exc: traceback.print_exc() JS9_ERROR = \"Error reading init templates: {}\".format(str(exc)) except JS9Error", "# <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link", "inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals())", "JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if not", "# <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script", "JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self, message=None):", "with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\")", "console.log('loaded JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9", "URL used to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" #", "import message, error # init JS9 configuration # js9 source directory DIRNAME =", "available yet. Determines paths and starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import", "message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available yet.", "JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not", "code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try:", "JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX", "inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR = \"Error reading", "# init JS9 configuration # js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR =", "display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet'", "= exc.message # on error, init code replaced by error message if JS9_ERROR:", "Javascript can be injected\"\"\" # from IPython.display import Javascript, display # display(Javascript(\"\"\" #", "# Javascript code read from local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC =", "= os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None", "__init__(self, message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available", "src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> #", "{}\".format(str(exc)) except JS9Error as exc: if exc.message: JS9_ERROR = exc.message # on error,", "# from IPython.display import Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon'", "# display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'>", "to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre", "def __init__(self, message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not", "not exist\") message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX", "helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR =", "import os, os.path, traceback from iglesia.utils import message, error # init JS9 configuration", "open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as", "try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"),", "display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> #", "<script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript'", "JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script", "# js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\")", "type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'>", "Determines paths and starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia global", "<script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript'", "def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available yet. Determines paths and starts", "# URL used to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\"", "settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def", "exc.message # on error, init code replaced by error message if JS9_ERROR: error(f\"JS9", "type='text/javascript'> console.log('loaded JS9 prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'>", "code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre aux dir JS9_INSTALL_PREFIX", "console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> #", "radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"),", "raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global", "def init_js9(): # \"\"\"Final initialization, when Javascript can be injected\"\"\" # from IPython.display", "rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'>", "JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self, message=None): self.message = message def preinit_js9():", "error # init JS9 configuration # js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR", "JS9_ERROR = exc.message # on error, init code replaced by error message if", "class JS9Error(Exception): def __init__(self, message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization, when Javascript", "src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script>", "JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise", "injected\"\"\" # from IPython.display import Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut", "global radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT", "iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR", "\"Error reading init templates: {}\".format(str(exc)) except JS9Error as exc: if exc.message: JS9_ERROR =", "<script type='text/javascript'> console.log('loaded JS9 prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script", "type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner plugin') </script> # <script type='text/javascript'", "exist\") message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global", "href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript'", "1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script>", "type='text/javascript'> console.log('loaded JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded", "global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX", "type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet'", "JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner", "try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9", "templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals())", "as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC =", "Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css'", "<link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css'", "paths and starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT,", "iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does", "<script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner plugin') </script> # <script", "message, error # init JS9 configuration # js9 source directory DIRNAME = os.path.dirname(__file__)", "= os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None # Javascript code read from local", "rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'>", "= \"\" class JS9Error(Exception): def __init__(self, message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization,", "RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre aux dir JS9_INSTALL_PREFIX =", "console.log('loaded JS9 prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded", "directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT", "templates: {}\".format(str(exc)) except JS9Error as exc: if exc.message: JS9_ERROR = exc.message # on", "# on error, init code replaced by error message if JS9_ERROR: error(f\"JS9 init", "\"\"\"Pre-initialization, when Javascript is not available yet. Determines paths and starts helper processs\"\"\"", "JS9 configuration # js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR", "src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> #", "load templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC =", "message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization,", "starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR", "radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try:", "# URL used to access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL", "</script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> #", "message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC", "JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global", "HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with open(os.path.join(DIRNAME,", "global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT try: global JS9_ERROR if", "init code replaced by error message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") #", "error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization, when Javascript can be injected\"\"\"", "traceback from iglesia.utils import message, error # init JS9 configuration # js9 source", "dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9 code JS9_SCRIPT_PREFIX =", "error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization, when Javascript can", "Javascript code read from local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC", "yet. Determines paths and starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia", "and starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR", "not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install in {JS9_DIR}\") global", "2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script>", "<script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script", "preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available yet. Determines paths and starts helper", "JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" #", "URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to", "= f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\"", "open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc: traceback.print_exc()", "<script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components') </script> # <script type='text/javascript'", "JS9Error as exc: if exc.message: JS9_ERROR = exc.message # on error, init code", "JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None # Javascript code read from", "install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC", "access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9", "aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9 code JS9_SCRIPT_PREFIX", "init templates: {}\".format(str(exc)) except JS9Error as exc: if exc.message: JS9_ERROR = exc.message #", "JS9Error(Exception): def __init__(self, message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is", "used to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load", "initialization, when Javascript can be injected\"\"\" # from IPython.display import Javascript, display #", "</script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner plugin') </script>", "<script type='text/javascript'> console.log('loaded JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'>", "f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp:", "access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre aux", "access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init", "JS9_ERROR if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install in", "JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try: with", "code read from local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC =", "prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs", "href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded", "# <script type='text/javascript'> console.log('loaded JS9 partner plugin') </script> # <script type='text/javascript' src='/static/js9colormaps.js'></script>\\ #", "os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None # Javascript code read from local settings", "message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available yet. Determines paths and", "= f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as", "self.message = message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available yet. Determines", "JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used", "# URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used", "JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre code", "JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization, when Javascript", "or None JS9_HELPER_PORT = None # Javascript code read from local settings file", "JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self, message=None): self.message = message", "JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None # Javascript", "read from local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\"", "# <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon'", "# <script type='text/javascript'> console.log('loaded JS9 prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> #", "if not os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install in {JS9_DIR}\")", "exc: if exc.message: JS9_ERROR = exc.message # on error, init code replaced by", "src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components') </script> #", "= radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try: with open(os.path.join(DIRNAME,", "= f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS", "local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception):", "global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre", "used to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access", "= message def preinit_js9(): \"\"\"Pre-initialization, when Javascript is not available yet. Determines paths", "on error, init code replaced by error message if JS9_ERROR: error(f\"JS9 init error:", "None JS9_HELPER_PORT = None # Javascript code read from local settings file JS9_LOCAL_SETTINGS", "os.path, traceback from iglesia.utils import message, error # init JS9 configuration # js9", "None # Javascript code read from local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC", "init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\") as inp: JS9_INIT_HTML_STATIC = inp.read().format(**globals()) with", "configuration # js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR =", "= f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" #", "radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\" # URL used to access radiopadre aux dir", "\"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR", "{JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX", "as exc: if exc.message: JS9_ERROR = exc.message # on error, init code replaced", "# \"\"\"Final initialization, when Javascript can be injected\"\"\" # from IPython.display import Javascript,", "IPython.display import Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'> #", "# <script type='text/javascript'> console.log('loaded JS9 components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script", "error, init code replaced by error message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\")", "in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global", "<link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs", "if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9(): # \"\"\"Final initialization, when", "src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner plugin') </script> # <script type='text/javascript' src='/static/js9colormaps.js'></script>\\", "Javascript is not available yet. Determines paths and starts helper processs\"\"\" global radiopadre_kernel", "JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX", "= None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self, message=None): self.message", "prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript'", "None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None # Javascript code read", "inp.read().format(**globals()) with open(os.path.join(DIRNAME, \"js9-init-dynamic-template.html\"), \"rt\") as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as", "# <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 1') </script> #", "# <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script>", "\"\"\"Final initialization, when Javascript can be injected\"\"\" # from IPython.display import Javascript, display", "used to access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to", "None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class JS9Error(Exception): def __init__(self, message=None): self.message =", "# <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9", "# <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script", "except JS9Error as exc: if exc.message: JS9_ERROR = exc.message # on error, init", "type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 2')</script> # <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script>", "= None # Javascript code read from local settings file JS9_LOCAL_SETTINGS = None", "to access JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated", "reading init templates: {}\".format(str(exc)) except JS9Error as exc: if exc.message: JS9_ERROR = exc.message", "# <script type='text/javascript' src='/static/js9-www/js9support.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> #", "# <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9 components') </script> # <script", "global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global", "by error message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9(): #", "be injected\"\"\" # from IPython.display import Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon'", "JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR = \"Error reading init", "replaced by error message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def init_js9():", "icon' href='/static/js9-www/favicon.ico'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> #", "code replaced by error message if JS9_ERROR: error(f\"JS9 init error: {JS9_ERROR}\") # def", "as inp: JS9_INIT_HTML_DYNAMIC = inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR = \"Error", "JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML try: with open(os.path.join(DIRNAME, \"js9-init-static-template.html\"), \"rt\")", "inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR = \"Error reading init templates: {}\".format(str(exc))", "JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access", "not available yet. Determines paths and starts helper processs\"\"\" global radiopadre_kernel import radiopadre_kernel", "global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX", "source directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None", "= \"Error reading init templates: {}\".format(str(exc)) except JS9Error as exc: if exc.message: JS9_ERROR", "JS9 prefs 1') </script> # <script type='text/javascript' src='/files/.radiopadre-session/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9", "JS9_HELPER_PORT = None # Javascript code read from local settings file JS9_LOCAL_SETTINGS =", "except Exception as exc: traceback.print_exc() JS9_ERROR = \"Error reading init templates: {}\".format(str(exc)) except", "from iglesia.utils import message, error # init JS9 configuration # js9 source directory", "type='text/css' rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> #", "from local settings file JS9_LOCAL_SETTINGS = None JS9_INIT_HTML_STATIC = JS9_INIT_HTML_DYNAMIC = \"\" class", "RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/{radiopadre_kernel.ABSROOTDIR}/.radiopadre\"", "JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL used to access radiopadre code RADIOPADRE_LOCAL_PREFIX =", "rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 1')", "components') </script> # <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner plugin')", "when Javascript can be injected\"\"\" # from IPython.display import Javascript, display # display(Javascript(\"\"\"", "from IPython.display import Javascript, display # display(Javascript(\"\"\" # <link type='image/x-icon' rel='shortcut icon' href='/static/js9-www/favicon.ico'>", "# <script type='text/javascript' src='/static/js9-www/js9.min.js'></script> # <script type='text/javascript' src='/static/js9-www/js9plugins.js'></script> # <script type='text/javascript'> console.log('loaded JS9", "<link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> #", "can be injected\"\"\" # from IPython.display import Javascript, display # display(Javascript(\"\"\" # <link", "RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS", "os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None #", "= inp.read().format(**globals()) except Exception as exc: traceback.print_exc() JS9_ERROR = \"Error reading init templates:", "\"\" class JS9Error(Exception): def __init__(self, message=None): self.message = message def preinit_js9(): \"\"\"Pre-initialization, when", "global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\" # URL", "# def init_js9(): # \"\"\"Final initialization, when Javascript can be injected\"\"\" # from", "href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script type='text/javascript'> console.log('loaded JS9 prefs 1') </script>", "does not exist\") message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX global RADIOPADRE_LOCAL_PREFIX global", "processs\"\"\" global radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR", "JS9_ERROR = \"Error reading init templates: {}\".format(str(exc)) except JS9Error as exc: if exc.message:", "if exc.message: JS9_ERROR = exc.message # on error, init code replaced by error", "# <script type='text/javascript' src='/static/radiopadre-www/js9partners.js'></script> # <script type='text/javascript'> console.log('loaded JS9 partner plugin') </script> #", "rel='stylesheet' href='/static/js9-www/js9support.css'> # <link type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script", "DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT =", "os.path.exists(JS9_DIR): raise JS9Error(f\"{JS9_DIR} does not exist\") message(f\"Using JS9 install in {JS9_DIR}\") global RADIOPADRE_INSTALL_PREFIX", "init_js9(): # \"\"\"Final initialization, when Javascript can be injected\"\"\" # from IPython.display import", "init JS9 configuration # js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None", "global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/radiopadre-www\"", "is not available yet. Determines paths and starts helper processs\"\"\" global radiopadre_kernel import", "js9 source directory DIRNAME = os.path.dirname(__file__) JS9_DIR = None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or", "radiopadre_kernel import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT =", "import radiopadre_kernel import iglesia global JS9_HELPER_PORT, JS9_DIR JS9_DIR = iglesia.JS9_DIR JS9_HELPER_PORT = iglesia.JS9HELPER_PORT", "RADIOPADRE_LOCAL_PREFIX global JS9_INSTALL_PREFIX global JS9_INIT_HTML_STATIC global JS9_INIT_HTML_DYNAMIC global JS9_SCRIPT_PREFIX global JS9_LOCAL_SETTINGS RADIOPADRE_INSTALL_PREFIX =", "= None JS9_ERROR = os.environ.get(\"RADIOPADRE_JS9_ERROR\") or None JS9_HELPER_PORT = None # Javascript code", "JS9 code JS9_SCRIPT_PREFIX = radiopadre_kernel.SHADOW_URL_PREFIX JS9_LOCAL_SETTINGS = f\"{radiopadre_kernel.SESSION_URL}/js9prefs.js\" # load templated init HTML", "type='text/css' rel='stylesheet' href='/static/js9-www/js9.css'> # <link rel='apple-touch-icon' href='/static/js9-www/images/js9-apple-touch-icon.png'> # <script type='text/javascript' src='/static/js9-www/js9prefs.js'></script> # <script", "exc: traceback.print_exc() JS9_ERROR = \"Error reading init templates: {}\".format(str(exc)) except JS9Error as exc:", "to access radiopadre aux dir JS9_INSTALL_PREFIX = f\"{radiopadre_kernel.SHADOW_URL_PREFIX}/js9-www\" # URL used to access" ]
[ "packages = [\"idna\"] options = { 'build_exe': { 'packages': packages, }, } setup(", "}, } setup( name=\"Tweeter Sentiment Analysis\", options=options, version=\"1.0\", description='Tweeter tweets analysis', executables=executables )", "<gh_stars>0 from cx_Freeze import setup, Executable base = None executables = [Executable(\"Analysis.py\", base=base)]", "None executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options = { 'build_exe': {", "base=base)] packages = [\"idna\"] options = { 'build_exe': { 'packages': packages, }, }", "setup, Executable base = None executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options", "= [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options = { 'build_exe': { 'packages': packages,", "= None executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options = { 'build_exe':", "packages, }, } setup( name=\"Tweeter Sentiment Analysis\", options=options, version=\"1.0\", description='Tweeter tweets analysis', executables=executables", "[\"idna\"] options = { 'build_exe': { 'packages': packages, }, } setup( name=\"Tweeter Sentiment", "import setup, Executable base = None executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"]", "[Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options = { 'build_exe': { 'packages': packages, },", "{ 'packages': packages, }, } setup( name=\"Tweeter Sentiment Analysis\", options=options, version=\"1.0\", description='Tweeter tweets", "executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options = { 'build_exe': { 'packages':", "cx_Freeze import setup, Executable base = None executables = [Executable(\"Analysis.py\", base=base)] packages =", "{ 'build_exe': { 'packages': packages, }, } setup( name=\"Tweeter Sentiment Analysis\", options=options, version=\"1.0\",", "base = None executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options = {", "from cx_Freeze import setup, Executable base = None executables = [Executable(\"Analysis.py\", base=base)] packages", "Executable base = None executables = [Executable(\"Analysis.py\", base=base)] packages = [\"idna\"] options =", "options = { 'build_exe': { 'packages': packages, }, } setup( name=\"Tweeter Sentiment Analysis\",", "'build_exe': { 'packages': packages, }, } setup( name=\"Tweeter Sentiment Analysis\", options=options, version=\"1.0\", description='Tweeter", "'packages': packages, }, } setup( name=\"Tweeter Sentiment Analysis\", options=options, version=\"1.0\", description='Tweeter tweets analysis',", "= { 'build_exe': { 'packages': packages, }, } setup( name=\"Tweeter Sentiment Analysis\", options=options,", "= [\"idna\"] options = { 'build_exe': { 'packages': packages, }, } setup( name=\"Tweeter" ]
[]
[ "IN TIME ************** import numpy as np import pandas as pd import math", "np.float) # quantile for 95% confidence interval q = ss.norm.ppf(0.975) for n in", "(z_ < 0) | (z_ > 4*math.pi), 0, sin_) N_ = 1000 params_", "print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for i", "'y ~ z + D + D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula", "reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower", "0, 1) sin_ = np.zeros(len(z_)) for i in z_: sin_[i] = math.sin(0.5*z_[i]) T_", "= np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n in range(N_): y_ = 20", "Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient estimate for i in", "= np.linspace(-90, t_max, num = (t_max + 91), dtype = int) D_ =", "D + D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~ z", "(df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~ z + D + D*z', data", "1 else: in_ci[i, n] = 0 return params, bse, in_ci # Print results", "n in range(N_): y_ = 20 + 0.05*z_ + T_ + np.random.normal(0, 0.5,", "z_ = np.linspace(-90, t_max, num = (t_max + 91), dtype = int) D_", "coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate for i in range(len(params)):", "The last row shows the relative frequency of the event') print('that 0 (the", "z_ + D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper =", "4*math.pi), 0, sin_) N_ = 1000 params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_,", "'z': running, 'D': dummy}) reg1 = smf.ols(formula = 'y ~ z + D", "<reponame>marclipfert/student-project-antonia-marc<filename>auxiliary/simulation_study.py #*************************** SMALL SIMULATION STUDY ***************************** #************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN", "of D\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\"", "\"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5", "reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0 <=", "estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average", "# coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116)", "smf.ols(formula = 'y_ ~ z_ + D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower", "= np.zeros((5,N), np.float) # quantile for 95% confidence interval q = ss.norm.ppf(0.975) for", "dtype = int) D_ = np.where(z_ < 0, 0, 1) sin_ = np.zeros(len(z_))", "in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D']", "import numpy as np import pandas as pd import math as math import", "end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") #", "the estimated coefficient of D. The second row contains the') print('average of the", "= np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) # quantile", "D_}) reg = smf.ols(formula = 'y_ ~ z_ + D_ + D_*z_', data", "= reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper: in_ci_[n] = 1", "0, 0, 0, 0] ci_upper = [0, 0, 0, 0, 0] for i", "np.float) q_ = ss.norm.ppf(0.975) for n in range(N_): y_ = 20 + 0.05*z_", "print('Simulation Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\",", "= reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0", "data = df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~ z + D +", "i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] -", "years\", \"5 years\", \"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100) # Average coefficient", "to store results inside params = np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci", "= int) D_ = np.where(z_ < 0, 0, 1) sin_ = np.zeros(len(z_)) for", "params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] =", "row contains the') print('average of the corresponding standard error. The last row shows", "& (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~ z + D + D*z',", "print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient estimate for i in range(len(params)): print", "header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\"))", "statsmodels.formula.api as smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): #", "CONCEPTIONS IN TIME ************** import numpy as np import pandas as pd import", "= 'y ~ z + D + D*z', data = df).fit(cov_type='HC1') reg2 =", "reg3 = smf.ols(formula = 'y ~ z + D + D*z', data =", "ci_lower = [0, 0, 0, 0, 0] ci_upper = [0, 0, 0, 0,", "np.float) bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) # quantile for 95%", "in z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0) | (z_", "= ss.norm.ppf(0.975) for n in range(N): y = 20 + 0.05*running + treatment", "\") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for", "= pd.DataFrame(data = {'y': y_, 'z': z_, 'D': D_}) reg = smf.ols(formula =", "scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty arrays to", "return params, bse, in_ci # Print results def print_simulation_results(params, bse, in_ci, N): print('Simulation", "(5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12 months\", \"9 months\", \"3 months\"))", "+ T_ + np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data = {'y': y_, 'z':", "the relative frequency of the event') print('that 0 (the overall effect) was included", "dummy}) reg1 = smf.ols(formula = 'y ~ z + D + D*z', data", "df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~ z + D + D*z', data", "coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()),", "of D. The second row contains the') print('average of the corresponding standard error.", "< 0, 0, 1) sin_ = np.zeros(len(z_)) for i in z_: sin_[i] =", "= 20 + 0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data", "D_ = np.where(z_ < 0, 0, 1) sin_ = np.zeros(len(z_)) for i in", "print('that 0 (the overall effect) was included in the 95%-confidence interval.') # increase", "ci_upper = [0, 0, 0, 0, 0] for i in range(5): params[i,n] =", "for n in range(N_): y_ = 20 + 0.05*z_ + T_ + np.random.normal(0,", "TIME ************** import numpy as np import pandas as pd import math as", "= reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0", "+ D + D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula =", "error. The last row shows the relative frequency of the event') print('that 0", "(the overall effect) was included in the 95%-confidence interval.') # increase timespan def", "shows the relative frequency of the event') print('that 0 (the overall effect) was", "in_ci # Print results def print_simulation_results(params, bse, in_ci, N): print('Simulation Study - Results')", "Int.\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\"", "z + D + D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y", "print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient estimate for", "\"5 years\", \"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated", "timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num = (t_max + 91), dtype", "int) D_ = np.where(z_ < 0, 0, 1) sin_ = np.zeros(len(z_)) for i", "D\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \")", "<= 0 <= ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i, n] = 0", "reg1 = smf.ols(formula = 'y ~ z + D + D*z', data =", "\"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12 months\", \"9 months\", \"3", "\") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient", "sin_ = np.zeros(len(z_)) for i in z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where(", "y_, 'z': z_, 'D': D_}) reg = smf.ols(formula = 'y_ ~ z_ +", "{'y': y_, 'z': z_, 'D': D_}) reg = smf.ols(formula = 'y_ ~ z_", "else: in_ci[i, n] = 0 return params, bse, in_ci # Print results def", "q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper: in_ci_[n] = 1 else: in_ci_[n] =", "91), dtype = int) D_ = np.where(z_ < 0, 0, 1) sin_ =", "np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) # quantile for 95% confidence interval q", "in_ci[i, n] = 0 return params, bse, in_ci # Print results def print_simulation_results(params,", "the event') print('that 0 (the overall effect) was included in the 95%-confidence interval.')", "+ D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~", "months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient estimate", "increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num = (t_max + 91), dtype = int)", "reg3, reg4, reg5] ci_lower = [0, 0, 0, 0, 0] ci_upper = [0,", "= [0, 0, 0, 0, 0] for i in range(5): params[i,n] = reg_list[i].params['D']", "+ treatment + np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data = {'y': y, 'z':", "+ D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~", "np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n in range(N_): y_ = 20 +", "***************************** #************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME ************** import numpy as", "D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper = [] params_[n]", "= reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D']", "(df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~ z + D + D*z', data", "event') print('that 0 (the overall effect) was included in the 95%-confidence interval.') #", "ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <=", "(df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4, reg5] ci_lower = [0, 0, 0,", "i in z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0) |", "increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num = (t_max + 91),", "= 'y_ ~ z_ + D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower =", "= reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if", "print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate for i in range(len(params)): print", "- q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper:", "of the estimated coefficient of D. The second row contains the') print('average of", "TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME ************** import numpy as np import", "np.zeros((5,N), np.float) # quantile for 95% confidence interval q = ss.norm.ppf(0.975) for n", "ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty arrays to store results", "len(running)) df = pd.DataFrame(data = {'y': y, 'z': running, 'D': dummy}) reg1 =", "the average of the estimated coefficient of D. The second row contains the')", "= smf.ols(formula = 'y_ ~ z_ + D_ + D_*z_', data = df_).fit(cov_type='HC1')", "D. The second row contains the') print('average of the corresponding standard error. The", "'y ~ z + D + D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3", "\"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10", "(z_ > 4*math.pi), 0, sin_) N_ = 1000 params_ = np.zeros(N_, np.float) bse_", "= np.where(z_ < 0, 0, 1) sin_ = np.zeros(len(z_)) for i in z_:", "print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\",", "import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty arrays", "0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data = {'y': y_,", "Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for i in range(len(params)): print", "0, 0, 0, 0] for i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] =", "treatment, N): # create empty arrays to store results inside params = np.zeros((5,N),", "overall effect) was included in the 95%-confidence interval.') # increase timespan def increase_available_timespan(t_max):", "+ 91), dtype = int) D_ = np.where(z_ < 0, 0, 1) sin_", "params, bse, in_ci # Print results def print_simulation_results(params, bse, in_ci, N): print('Simulation Study", "contains the') print('average of the corresponding standard error. The last row shows the", "data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~ z +", "data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~ z +", "math import statsmodels.formula.api as smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment,", "# coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\"", "in_ci = np.zeros((5,N), np.float) # quantile for 95% confidence interval q = ss.norm.ppf(0.975)", "\"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for i in", "1000 params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float)", "SIMULATION STUDY ***************************** #************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME ************** import", "= smf.ols(formula = 'y ~ z + D + D*z', data = df).fit(cov_type='HC1')", "z + D + D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula", "# header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD", "df = pd.DataFrame(data = {'y': y, 'z': running, 'D': dummy}) reg1 = smf.ols(formula", "print('The first row contains the average of the estimated coefficient of D. The", "0] for i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] =", "95%-confidence interval.') # increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num =", "D_*z_', data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper = [] params_[n] = reg.params['D_']", "ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <=", "y = 20 + 0.05*running + treatment + np.random.normal(0, 0.5, len(running)) df =", "= [] ci_upper = [] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower =", "sin_) N_ = 1000 params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_", "D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~ z", "reg = smf.ols(formula = 'y_ ~ z_ + D_ + D_*z_', data =", "math as math import statsmodels.formula.api as smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running,", "TREATMENT: MOVE UP CONCEPTIONS IN TIME ************** import numpy as np import pandas", "end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\"", "q = ss.norm.ppf(0.975) for n in range(N): y = 20 + 0.05*running +", "+ D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper = []", "reg4, reg5] ci_lower = [0, 0, 0, 0, 0] ci_upper = [0, 0,", "D + D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y", "D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4, reg5]", "for i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D']", "i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0", "- q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]:", "q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i,", "results def print_simulation_results(params, bse, in_ci, N): print('Simulation Study - Results') print('\\u2014'*100) # header", "in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"),", "np.float) bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for", "smf.ols(formula = 'y ~ z + D + D*z', data = df.loc[(df['z']>-13) &", "The second row contains the') print('average of the corresponding standard error. The last", "# quantile for 95% confidence interval q = ss.norm.ppf(0.975) for n in range(N):", "for n in range(N): y = 20 + 0.05*running + treatment + np.random.normal(0,", "np import pandas as pd import math as math import statsmodels.formula.api as smf", "= ss.norm.ppf(0.975) for n in range(N_): y_ = 20 + 0.05*z_ + T_", "data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~ D', data", "'y ~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3,", "params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper =", "df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~ z + D +", "num = (t_max + 91), dtype = int) D_ = np.where(z_ < 0,", "contains the average of the estimated coefficient of D. The second row contains", "in range(N): y = 20 + 0.05*running + treatment + np.random.normal(0, 0.5, len(running))", "smf.ols(formula = 'y ~ z + D + D*z', data = df).fit(cov_type='HC1') reg2", "= df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4, reg5] ci_lower =", "df_ = pd.DataFrame(data = {'y': y_, 'z': z_, 'D': D_}) reg = smf.ols(formula", "[] ci_upper = [] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_']", "~ z_ + D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper", "i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first", "bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) # quantile for 95% confidence", "if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i, n]", "z + D + D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula", "+ D_*z_', data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper = [] params_[n] =", "+ D + D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula =", "of the event') print('that 0 (the overall effect) was included in the 95%-confidence", "print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate", "np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data = {'y': y_, 'z': z_, 'D': D_})", "0 return params, bse, in_ci # Print results def print_simulation_results(params, bse, in_ci, N):", "bse, in_ci, N): print('Simulation Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD", "= df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~ z + D + D*z',", "as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty arrays to store", "'y ~ z + D + D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5", "Print results def print_simulation_results(params, bse, in_ci, N): print('Simulation Study - Results') print('\\u2014'*100) #", "of the corresponding standard error. The last row shows the relative frequency of", "z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0) | (z_ >", "for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The", "0, 0] ci_upper = [0, 0, 0, 0, 0] for i in range(5):", "was included in the 95%-confidence interval.') # increase timespan def increase_available_timespan(t_max): z_ =", "estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average", "= 'y ~ z + D + D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1')", "+ np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data = {'y': y, 'z': running, 'D':", "0 (the overall effect) was included in the 95%-confidence interval.') # increase timespan", "df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~ z + D +", "1) sin_ = np.zeros(len(z_)) for i in z_: sin_[i] = math.sin(0.5*z_[i]) T_ =", "def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty arrays to store results inside", "= {'y': y, 'z': running, 'D': dummy}) reg1 = smf.ols(formula = 'y ~", "print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"),", "Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD", "params = np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) #", "= 1000 params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_,", "Error\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \")", "95% confidence interval q = ss.norm.ppf(0.975) for n in range(N): y = 20", "# Print results def print_simulation_results(params, bse, in_ci, N): print('Simulation Study - Results') print('\\u2014'*100)", "D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~ z", "20 + 0.05*running + treatment + np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data =", "& (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~ D', data = df.loc[(df['z']>-4) &", "q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper: in_ci_[n]", "= df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~ z + D", "months\", \"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") #", "'y_ ~ z_ + D_ + D_*z_', data = df_).fit(cov_type='HC1') ci_lower = []", "0.5, len(running)) df = pd.DataFrame(data = {'y': y, 'z': running, 'D': dummy}) reg1", "relative frequency of the event') print('that 0 (the overall effect) was included in", "for i in z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0)", "reg4 = smf.ols(formula = 'y ~ z + D + D*z', data =", "df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4, reg5] ci_lower = [0,", "0.95-Conf. Int.\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ),", "0, 0, 0] ci_upper = [0, 0, 0, 0, 0] for i in", "in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n in range(N_): y_ =", "= 'y ~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2,", "# Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for i in range(len(params)):", "= smf.ols(formula = 'y ~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list =", "\"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12", "pd import math as math import statsmodels.formula.api as smf import scipy.stats as ss", "), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first row contains the average of", "= 1 else: in_ci[i, n] = 0 return params, bse, in_ci # Print", "ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i, n] =", "import math as math import statsmodels.formula.api as smf import scipy.stats as ss def", "the corresponding standard error. The last row shows the relative frequency of the", "interval.') # increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num = (t_max", "SMALL SIMULATION STUDY ***************************** #************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME **************", "0, 0] for i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i]", "+ q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper: in_ci_[n] = 1 else: in_ci_[n]", "bse, in_ci # Print results def print_simulation_results(params, bse, in_ci, N): print('Simulation Study -", "reg_list = [reg1, reg2, reg3, reg4, reg5] ci_lower = [0, 0, 0, 0,", "range(N): y = 20 + 0.05*running + treatment + np.random.normal(0, 0.5, len(running)) df", "\"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12 months\", \"9", "# Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient estimate for i", "inside params = np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float)", "Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate for i in", "as np import pandas as pd import math as math import statsmodels.formula.api as", "[0, 0, 0, 0, 0] ci_upper = [0, 0, 0, 0, 0] for", "np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975)", "data = df_).fit(cov_type='HC1') ci_lower = [] ci_upper = [] params_[n] = reg.params['D_'] bse_[n]", "20 + 0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data =", "0] ci_upper = [0, 0, 0, 0, 0] for i in range(5): params[i,n]", "coefficient of D. The second row contains the') print('average of the corresponding standard", "************** import numpy as np import pandas as pd import math as math", "n] = 0 return params, bse, in_ci # Print results def print_simulation_results(params, bse,", "as math import statsmodels.formula.api as smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy,", "N_ = 1000 params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_ =", "z_, 'D': D_}) reg = smf.ols(formula = 'y_ ~ z_ + D_ +", "MOVE UP CONCEPTIONS IN TIME ************** import numpy as np import pandas as", "= np.zeros(len(z_)) for i in z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_", "print_simulation_results(params, bse, in_ci, N): print('Simulation Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\",", "ci_upper = reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper: in_ci_[n] =", "print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first row contains the", "for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient", "reg2, reg3, reg4, reg5] ci_lower = [0, 0, 0, 0, 0] ci_upper =", "+ q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n] = 1 else:", "T_ = np.where( (z_ < 0) | (z_ > 4*math.pi), 0, sin_) N_", "standard error. The last row shows the relative frequency of the event') print('that", "corresponding standard error. The last row shows the relative frequency of the event')", "print(\" \"*116) print('\\u2014'*100) print('The first row contains the average of the estimated coefficient", "('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient", "effect) was included in the 95%-confidence interval.') # increase timespan def increase_available_timespan(t_max): z_", "N): # create empty arrays to store results inside params = np.zeros((5,N), np.float)", "\"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate for", "end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first row contains the average of the", "quantile for 95% confidence interval q = ss.norm.ppf(0.975) for n in range(N): y", "in_ci, N): print('Simulation Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\",", "= smf.ols(formula = 'y ~ z + D + D*z', data = df.loc[(df['z']>-13)", "& (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4, reg5] ci_lower = [0, 0,", "the 95%-confidence interval.') # increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num", "ss.norm.ppf(0.975) for n in range(N): y = 20 + 0.05*running + treatment +", "range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i]", "for 95% confidence interval q = ss.norm.ppf(0.975) for n in range(N): y =", "for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient", "~ z + D + D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 =", "average of the estimated coefficient of D. The second row contains the') print('average", "coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116)", "i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard", "reg2 = smf.ols(formula = 'y ~ z + D + D*z', data =", "= 'y ~ z + D + D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1')", "y_ = 20 + 0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_)) df_ =", "interval q = ss.norm.ppf(0.975) for n in range(N): y = 20 + 0.05*running", "+ 0.05*running + treatment + np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data = {'y':", "# create empty arrays to store results inside params = np.zeros((5,N), np.float) bse", "[reg1, reg2, reg3, reg4, reg5] ci_lower = [0, 0, 0, 0, 0] ci_upper", "= np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n in", "coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) #", "0, sin_) N_ = 1000 params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float)", "import pandas as pd import math as math import statsmodels.formula.api as smf import", "+ D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y ~", "last row shows the relative frequency of the event') print('that 0 (the overall", "~ z + D + D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 =", "= [] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_']", "[] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper", "in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N", "= 20 + 0.05*running + treatment + np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data", "+ D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~ z +", "0, 0, 1) sin_ = np.zeros(len(z_)) for i in z_: sin_[i] = math.sin(0.5*z_[i])", "\"10 years\", \"5 years\", \"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100) # Average", "reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i]", "store results inside params = np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci =", "+ D + D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula =", "reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] +", "row shows the relative frequency of the event') print('that 0 (the overall effect)", "<= 0 <= ci_upper: in_ci_[n] = 1 else: in_ci_[n] = 0 return params_", "smf.ols(formula = 'y ~ z + D + D*z', data = df.loc[(df['z']>-31) &", "pandas as pd import math as math import statsmodels.formula.api as smf import scipy.stats", "ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n]", "0, 0, 0] for i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n] = reg_list[i].bse['D']", "math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0) | (z_ > 4*math.pi), 0, sin_)", "> 4*math.pi), 0, sin_) N_ = 1000 params_ = np.zeros(N_, np.float) bse_ =", "reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] +", "np.where( (z_ < 0) | (z_ > 4*math.pi), 0, sin_) N_ = 1000", "pd.DataFrame(data = {'y': y, 'z': running, 'D': dummy}) reg1 = smf.ols(formula = 'y", "in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first row", "np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data = {'y': y, 'z': running, 'D': dummy})", "(df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1')", "#************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME ************** import numpy as np", "reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <=", "in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in", "as smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create", "~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4,", "np.linspace(-90, t_max, num = (t_max + 91), dtype = int) D_ = np.where(z_", "smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty", "= 0 return params, bse, in_ci # Print results def print_simulation_results(params, bse, in_ci,", "np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) # quantile for", "range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf.", "smf.ols(formula = 'y ~ z + D + D*z', data = df.loc[(df['z']>-10) &", "& (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~ z + D + D*z',", "end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\"", "the') print('average of the corresponding standard error. The last row shows the relative", "('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\")", "second row contains the') print('average of the corresponding standard error. The last row", "data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1, reg2, reg3, reg4, reg5] ci_lower", "\") print(\" \"*116) print('\\u2014'*100) print('The first row contains the average of the estimated", "np.where(z_ < 0, 0, 1) sin_ = np.zeros(len(z_)) for i in z_: sin_[i]", "= [0, 0, 0, 0, 0] ci_upper = [0, 0, 0, 0, 0]", "+ np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data = {'y': y_, 'z': z_, 'D':", "df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~ D', data = df.loc[(df['z']>-4)", "- Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\",", "(1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\",", "STUDY ***************************** #************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME ************** import numpy", "0 <= ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i, n] = 0 return", "np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n in range(N_):", "df_).fit(cov_type='HC1') ci_lower = [] ci_upper = [] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_']", "range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\")", "z + D + D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula", "n] = 1 else: in_ci[i, n] = 0 return params, bse, in_ci #", "row contains the average of the estimated coefficient of D. The second row", "0.05*running + treatment + np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data = {'y': y,", "running, 'D': dummy}) reg1 = smf.ols(formula = 'y ~ z + D +", "#*************************** SMALL SIMULATION STUDY ***************************** #************* TIME-VARYING TREATMENT: MOVE UP CONCEPTIONS IN TIME", "[0, 0, 0, 0, 0] for i in range(5): params[i,n] = reg_list[i].params['D'] bse[i,n]", "in_ci[i, n] = 1 else: in_ci[i, n] = 0 return params, bse, in_ci", "('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first row contains the average", "print ('{:>10.4f}'.format(params[i,:].mean()), end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") #", "N): print('Simulation Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD", "{'y': y, 'z': running, 'D': dummy}) reg1 = smf.ols(formula = 'y ~ z", "+ 0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data = {'y':", "D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~ D',", "= np.where( (z_ < 0) | (z_ > 4*math.pi), 0, sin_) N_ =", "q_ = ss.norm.ppf(0.975) for n in range(N_): y_ = 20 + 0.05*z_ +", "ss.norm.ppf(0.975) for n in range(N_): y_ = 20 + 0.05*z_ + T_ +", "end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \")", "= smf.ols(formula = 'y ~ z + D + D*z', data = df.loc[(df['z']>-31)", "D + D*z', data = df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y", "dummy, treatment, N): # create empty arrays to store results inside params =", "frequency of the event') print('that 0 (the overall effect) was included in the", "print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100)", "= np.zeros((5,N), np.float) in_ci = np.zeros((5,N), np.float) # quantile for 95% confidence interval", "end=\" \") print(\" \"*116) # Average coefficient print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate", "= df.loc[(df['z']>-10) & (df['z']<9)]).fit(cov_type='HC1') reg5 = smf.ols(formula = 'y ~ D', data =", "create empty arrays to store results inside params = np.zeros((5,N), np.float) bse =", "0.5, len(z_)) df_ = pd.DataFrame(data = {'y': y_, 'z': z_, 'D': D_}) reg", "range(N_): y_ = 20 + 0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_)) df_", "import statsmodels.formula.api as smf import scipy.stats as ss def simulating_results_from_different_bandwidths(running, dummy, treatment, N):", "confidence interval q = ss.norm.ppf(0.975) for n in range(N): y = 20 +", "ci_lower <= 0 <= ci_upper: in_ci_[n] = 1 else: in_ci_[n] = 0 return", "reg5] ci_lower = [0, 0, 0, 0, 0] ci_upper = [0, 0, 0,", "np.zeros(len(z_)) for i in z_: sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_ <", ".format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\",", "y, 'z': running, 'D': dummy}) reg1 = smf.ols(formula = 'y ~ z +", "= reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_']", "coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient estimate for i in range(len(params)):", "results inside params = np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float) in_ci = np.zeros((5,N),", "D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~ z + D", "sin_[i] = math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0) | (z_ > 4*math.pi),", "ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i, n] = 0 return params, bse,", "~ z + D + D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 =", "\"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of", "# Average coefficient print('{:<25s}'.format(\"0 in 0.95-Conf. Int.\"), end=\"\") # coefficient estimate for i", "treatment + np.random.normal(0, 0.5, len(running)) df = pd.DataFrame(data = {'y': y, 'z': running,", "+ D + D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula = 'y ~", "= reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D'] if", "(3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12 months\",", "# increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num = (t_max +", "= df_).fit(cov_type='HC1') ci_lower = [] ci_upper = [] params_[n] = reg.params['D_'] bse_[n] =", "reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n] = 1", "in range(N_): y_ = 20 + 0.05*z_ + T_ + np.random.normal(0, 0.5, len(z_))", "np.float) in_ci = np.zeros((5,N), np.float) # quantile for 95% confidence interval q =", "arrays to store results inside params = np.zeros((5,N), np.float) bse = np.zeros((5,N), np.float)", "= pd.DataFrame(data = {'y': y, 'z': running, 'D': dummy}) reg1 = smf.ols(formula =", "t_max, num = (t_max + 91), dtype = int) D_ = np.where(z_ <", "UP CONCEPTIONS IN TIME ************** import numpy as np import pandas as pd", "bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n", "= [reg1, reg2, reg3, reg4, reg5] ci_lower = [0, 0, 0, 0, 0]", "(4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\", \"12 months\", \"9 months\",", "'D': D_}) reg = smf.ols(formula = 'y_ ~ z_ + D_ + D_*z_',", "estimate for i in range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100)", "= {'y': y_, 'z': z_, 'D': D_}) reg = smf.ols(formula = 'y_ ~", "Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD", "bse[i,n] = reg_list[i].bse['D'] ci_lower[i] = reg_list[i].params['D'] - q*reg_list[i].bse['D'] ci_upper[i] = reg_list[i].params['D'] + q*reg_list[i].bse['D']", "reg5 = smf.ols(formula = 'y ~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list", "q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i,", ".format(\"\", \"10 years\", \"5 years\", \"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100) #", "empty arrays to store results inside params = np.zeros((5,N), np.float) bse = np.zeros((5,N),", "'y ~ z + D + D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4", "print('{:<25s}'.format(\"Standard Error\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\"", "pd.DataFrame(data = {'y': y_, 'z': z_, 'D': D_}) reg = smf.ols(formula = 'y_", "= reg_list[i].params['D'] + q*reg_list[i].bse['D'] if ci_lower[i] <= 0 <= ci_upper[i]: in_ci[i, n] =", "np.float) in_ci_ = np.zeros(N_, np.float) q_ = ss.norm.ppf(0.975) for n in range(N_): y_", "as pd import math as math import statsmodels.formula.api as smf import scipy.stats as", "~ z + D + D*z', data = df).fit(cov_type='HC1') reg2 = smf.ols(formula =", "len(z_)) df_ = pd.DataFrame(data = {'y': y_, 'z': z_, 'D': D_}) reg =", "# coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116)", "= (t_max + 91), dtype = int) D_ = np.where(z_ < 0, 0,", "= math.sin(0.5*z_[i]) T_ = np.where( (z_ < 0) | (z_ > 4*math.pi), 0,", "if ci_lower <= 0 <= ci_upper: in_ci_[n] = 1 else: in_ci_[n] = 0", "numpy as np import pandas as pd import math as math import statsmodels.formula.api", "< 0) | (z_ > 4*math.pi), 0, sin_) N_ = 1000 params_ =", "Coef. of D\"), end=\"\") # coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(params[i,:].mean()),", "T_ + np.random.normal(0, 0.5, len(z_)) df_ = pd.DataFrame(data = {'y': y_, 'z': z_,", "ci_lower = [] ci_upper = [] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower", "years\", \"12 months\", \"9 months\", \"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef.", "def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max, num = (t_max + 91), dtype =", "print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"RDD (1)\", \"RDD (2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}'", "= df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1') reg3 = smf.ols(formula = 'y ~ z + D", "smf.ols(formula = 'y ~ D', data = df.loc[(df['z']>-4) & (df['z']<3)]).fit(cov_type='HC1') reg_list = [reg1,", "<= ci_upper[i]: in_ci[i, n] = 1 else: in_ci[i, n] = 0 return params,", "(2)\", \"RDD (3)\", \"RDD (4)\", \"RDD (5)\")) print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}' .format(\"\", \"10 years\", \"5 years\",", "in the 95%-confidence interval.') # increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90, t_max,", "print('average of the corresponding standard error. The last row shows the relative frequency", "n in range(N): y = 20 + 0.05*running + treatment + np.random.normal(0, 0.5,", "params_ = np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_", "estimated coefficient of D. The second row contains the') print('average of the corresponding", "simulating_results_from_different_bandwidths(running, dummy, treatment, N): # create empty arrays to store results inside params", "print('\\u2014'*100) print('The first row contains the average of the estimated coefficient of D.", "= 'y ~ z + D + D*z', data = df.loc[(df['z']>-31) & (df['z']<30)]).fit(cov_type='HC1')", "reg.params['D_'] + q_*reg.bse['D_'] if ci_lower <= 0 <= ci_upper: in_ci_[n] = 1 else:", "D + D*z', data = df.loc[(df['z']>-13) & (df['z']<12)]).fit(cov_type='HC1') reg4 = smf.ols(formula = 'y", "def print_simulation_results(params, bse, in_ci, N): print('Simulation Study - Results') print('\\u2014'*100) # header print('{:<22s}{:>14s}{:>14s}{:>14s}{:>14s}{:>14s}'", "ci_upper = [] params_[n] = reg.params['D_'] bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] -", "\"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\") # coefficient", "0) | (z_ > 4*math.pi), 0, sin_) N_ = 1000 params_ = np.zeros(N_,", "range(len(params)): print ('{:>10.4f}'.format(sum(in_ci[i,:])/N ), end=\" \") print(\" \"*116) print('\\u2014'*100) print('The first row contains", "months\", \"9 months\", \"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"),", "\"9 months\", \"3 months\")) print('\\u2014'*100) # Average coefficient print('{:<25s}'.format(\"Estimated Coef. of D\"), end=\"\")", "\"*116) print('\\u2014'*100) print('The first row contains the average of the estimated coefficient of", "= np.zeros(N_, np.float) bse_ = np.zeros(N_, np.float) in_ci_ = np.zeros(N_, np.float) q_ =", "(t_max + 91), dtype = int) D_ = np.where(z_ < 0, 0, 1)", "| (z_ > 4*math.pi), 0, sin_) N_ = 1000 params_ = np.zeros(N_, np.float)", "first row contains the average of the estimated coefficient of D. The second", "coefficient estimate for i in range(len(params)): print ('{:>10.4f}'.format(bse[i,:].mean()), end=\" \") print(\" \"*116) #", "'D': dummy}) reg1 = smf.ols(formula = 'y ~ z + D + D*z',", "'z': z_, 'D': D_}) reg = smf.ols(formula = 'y_ ~ z_ + D_", "= smf.ols(formula = 'y ~ z + D + D*z', data = df.loc[(df['z']>-10)", "bse_[n] = reg.bse['D_'] ci_lower = reg.params['D_'] - q_*reg.bse['D_'] ci_upper = reg.params['D_'] + q_*reg.bse['D_']", "included in the 95%-confidence interval.') # increase timespan def increase_available_timespan(t_max): z_ = np.linspace(-90," ]
[ "= fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource SOAP Toolkit API',", "for sdist if 'sdist' in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir", ":: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English',", "'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python", "sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'),", "Software Development :: Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep", "Independent', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries", "Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep api wrapper', requires=['zeep'], install_requires=['zeep'], test_suite='pycybersource.tests', )", "'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System", "from setuptools import setup, find_packages import pycybersource # fix permissions for sdist if", "OS Independent', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development ::", "import sys from setuptools import setup, find_packages import pycybersource # fix permissions for", "fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource SOAP", "English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.6', 'Topic", "SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status ::", "platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience ::", "for Cybersource SOAP Toolkit API \"\"\" import os import sys from setuptools import", "setup, find_packages import pycybersource # fix permissions for sdist if 'sdist' in sys.argv:", "with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A", "fix permissions for sdist if 'sdist' in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022',", "-R a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as", ":: Software Development :: Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap", "Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent',", "BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language", "sys from setuptools import setup, find_packages import pycybersource # fix permissions for sdist", "Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status", "os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description =", "Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', ],", "permissions for sdist if 'sdist' in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8))", "wrapper for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[", "light wrapper for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD',", "os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0',", ":: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming", "= os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource',", "if 'sdist' in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__)", "setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>',", "author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended", "License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language ::", "API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 -", "description='A light wrapper for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'],", "classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License ::", "8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8')", "Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep api wrapper', requires=['zeep'], install_requires=['zeep'], test_suite='pycybersource.tests',", "Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep api wrapper', requires=['zeep'],", "'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language", "Toolkit API \"\"\" import os import sys from setuptools import setup, find_packages import", "wrapper for Cybersource SOAP Toolkit API \"\"\" import os import sys from setuptools", "fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource SOAP Toolkit API', author='<NAME>',", "'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries ::", "find_packages import pycybersource # fix permissions for sdist if 'sdist' in sys.argv: os.system('chmod", "Cybersource SOAP Toolkit API \"\"\" import os import sys from setuptools import setup,", "light wrapper for Cybersource SOAP Toolkit API \"\"\" import os import sys from", "import os import sys from setuptools import setup, find_packages import pycybersource # fix", "name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='',", ":: Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep api wrapper',", "for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development", "Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3", "'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper", ":: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System ::", "import setup, find_packages import pycybersource # fix permissions for sdist if 'sdist' in", "API \"\"\" import os import sys from setuptools import setup, find_packages import pycybersource", "os import sys from setuptools import setup, find_packages import pycybersource # fix permissions", "Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',", "author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha',", "OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS", "version='0.1.2a0', description='A light wrapper for Cybersource SOAP Toolkit API', author='<NAME>', author_email='<EMAIL>', url='', platforms=['Platform", ":: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved ::", ":: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep api wrapper', requires=['zeep'], install_requires=['zeep'],", "sdist if 'sdist' in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir =", "os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb')", "base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8') setup(", "python \"\"\" A light wrapper for Cybersource SOAP Toolkit API \"\"\" import os", "3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD", "open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light", "setuptools import setup, find_packages import pycybersource # fix permissions for sdist if 'sdist'", "long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource SOAP Toolkit", "'rb') as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for", "url='', platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience", ".') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp: long_description", "a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, 'README.md'), 'rb') as fp:", ":: OS Independent', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development", ":: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.6',", "Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural", "Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating", "import pycybersource # fix permissions for sdist if 'sdist' in sys.argv: os.system('chmod -R", "license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License", "- Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License',", "Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python ::", "3.6', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource", "Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language ::", ":: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=['pycybersource'],", "as fp: long_description = fp.read().decode('utf-8') setup( name='pycybersource', version='0.1.2a0', description='A light wrapper for Cybersource", "#!/usr/bin/env python \"\"\" A light wrapper for Cybersource SOAP Toolkit API \"\"\" import", "Development :: Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment soap zeep api", "in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir,", "\"\"\" import os import sys from setuptools import setup, find_packages import pycybersource #", "Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved", "'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI", "'Topic :: Software Development :: Libraries :: Python Modules', ], packages=['pycybersource'], keywords='cybersource payment", "'sdist' in sys.argv: os.system('chmod -R a+rX .') os.umask(int('022', 8)) base_dir = os.path.dirname(__file__) with", "'Operating System :: OS Independent', 'Programming Language :: Python :: 3.6', 'Topic ::", "SOAP Toolkit API \"\"\" import os import sys from setuptools import setup, find_packages", "\"\"\" A light wrapper for Cybersource SOAP Toolkit API \"\"\" import os import", "Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python", "System :: OS Independent', 'Programming Language :: Python :: 3.6', 'Topic :: Software", "# fix permissions for sdist if 'sdist' in sys.argv: os.system('chmod -R a+rX .')", "A light wrapper for Cybersource SOAP Toolkit API \"\"\" import os import sys", "pycybersource # fix permissions for sdist if 'sdist' in sys.argv: os.system('chmod -R a+rX", ":: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules'," ]
[ "django.core.cache import cache from django_redis import get_redis_connection from goods.models import GoodsType from goods.models", "get(self, request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if context is None: #", "here. from django.views.generic import View from django.core.cache import cache from django_redis import get_redis_connection", "your views here. from django.views.generic import View from django.core.cache import cache from django_redis", "in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type,", "View from django.core.cache import cache from django_redis import get_redis_connection from goods.models import GoodsType", "动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners context = { 'types': types, 'goods_banners':", "= IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners =", "goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in", "获取用户购物车中的商品的数目 user = request.user cart_count = 0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key", "import render # Create your views here. from django.views.generic import View from django.core.cache", "cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user = request.user cart_count = 0 if user.is_authenticated():", "user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count =", "request.user cart_count = 0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count", "goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request):", "import IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页'''", "goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View):", "timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user = request.user cart_count = 0 if", "'promotin_banners': promotin_banners, } # 设置缓存 # key value timeout cache.set('index_page_data', context, 3600) #", "goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 # key value timeout cache.set('index_page_data', context, 3600)", "GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息", "获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息", "if context is None: # 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息", "from goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self,", "django.shortcuts import render # Create your views here. from django.views.generic import View from", "django.views.generic import View from django.core.cache import cache from django_redis import get_redis_connection from goods.models", "class IndexView(View): '''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if", "{ 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 # key value", "cart_count = conn.hlen(cart_key) else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return render(request, 'index.html',", "cart_count = 0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count =", "goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context", "views here. from django.views.generic import View from django.core.cache import cache from django_redis import", "获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners", "= IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type,", "conn.hlen(cart_key) else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return render(request, 'index.html', context) def", "display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners", "= title_banners context = { 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } #", "None: # 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index')", "from django.views.generic import View from django.core.cache import cache from django_redis import get_redis_connection from", "if user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count", "import get_redis_connection from goods.models import GoodsType from goods.models import IndexGoodsBanner from goods.models import", "<reponame>litaiji/dailyfresh<filename>dailyfresh/apps/goods/views.py from django.shortcuts import render # Create your views here. from django.views.generic import", "import View from django.core.cache import cache from django_redis import get_redis_connection from goods.models import", "# 获取用户购物车中的商品的数目 user = request.user cart_count = 0 if user.is_authenticated(): conn = get_redis_connection('default')", "request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if context is None: # 缓存中没有数据", "from django.core.cache import cache from django_redis import get_redis_connection from goods.models import GoodsType from", "# 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners =", "is None: # 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners =", "} # 设置缓存 # key value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user", "goods.models import GoodsType from goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models", "from goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class", "type.title_banners = title_banners context = { 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, }", "获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type", "IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data')", "= 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return", "context = cache.get('index_page_data') if context is None: # 缓存中没有数据 # 获取商品种类信息 types =", "def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if context is None:", "import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context =", "# 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners context = { 'types': types,", "cache.get('index_page_data') if context is None: # 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() #", "get_redis_connection from goods.models import GoodsType from goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner", "获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息 image_banners", "= 0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key)", "IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request): '''显示首页''' #", "'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 # key value timeout", "Create your views here. from django.views.generic import View from django.core.cache import cache from", "from django.shortcuts import render # Create your views here. from django.views.generic import View", "from goods.models import GoodsType from goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner from", "django_redis import get_redis_connection from goods.models import GoodsType from goods.models import IndexGoodsBanner from goods.models", "= image_banners type.title_banners = title_banners context = { 'types': types, 'goods_banners': goods_banners, 'promotin_banners':", "get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count = 0 # 组织上下文", "GoodsType from goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner", "= conn.hlen(cart_key) else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return render(request, 'index.html', context)", "else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return render(request, 'index.html', context) def post(self,", "获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners =", "context = { 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 #", "user = request.user cart_count = 0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key =", "type in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners =", "# Create your views here. from django.views.generic import View from django.core.cache import cache", "key value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user = request.user cart_count =", "= request.user cart_count = 0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id", "display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners context = { 'types':", "# 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') #", "# 尝试从缓存获取数据 context = cache.get('index_page_data') if context is None: # 缓存中没有数据 # 获取商品种类信息", "promotin_banners, } # 设置缓存 # key value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目", "= IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types:", "title_banners context = { 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存", "cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count)", "image_banners type.title_banners = title_banners context = { 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners,", "title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners context", "# key value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user = request.user cart_count", "设置缓存 # key value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user = request.user", "cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return render(request, 'index.html', context) def post(self, request):", "import cache from django_redis import get_redis_connection from goods.models import GoodsType from goods.models import", "= 0 # 组织上下文 context.update(cart_count=cart_count) return render(request, 'index.html', context) def post(self, request): pass", "# 设置缓存 # key value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user =", "= get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count = 0 #", "value timeout cache.set('index_page_data', context, 3600) # 获取用户购物车中的商品的数目 user = request.user cart_count = 0", "for type in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners", "cache from django_redis import get_redis_connection from goods.models import GoodsType from goods.models import IndexGoodsBanner", "# 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for", "3600) # 获取用户购物车中的商品的数目 user = request.user cart_count = 0 if user.is_authenticated(): conn =", "import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request): '''显示首页'''", "# 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息", "types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')", "= cache.get('index_page_data') if context is None: # 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all()", "import GoodsType from goods.models import IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models import", "from django_redis import get_redis_connection from goods.models import GoodsType from goods.models import IndexGoodsBanner from", "缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息", "# 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') #", "= { 'types': types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 # key", "IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')", "0 if user.is_authenticated(): conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else:", "image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners", "promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息 image_banners =", "render # Create your views here. from django.views.generic import View from django.core.cache import", "from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据", "context is None: # 缓存中没有数据 # 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners", "types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index')", "IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品展示信息 for type in types: #", "# 获取首页分类商品展示信息 for type in types: # 获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') #", "获取type种类首页分类商品的图片信息 image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息", "'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 # key value timeout cache.set('index_page_data', context,", "types, 'goods_banners': goods_banners, 'promotin_banners': promotin_banners, } # 设置缓存 # key value timeout cache.set('index_page_data',", "# 获取商品种类信息 types = GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners", "= IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners context =", "conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count = 0", "context, 3600) # 获取用户购物车中的商品的数目 user = request.user cart_count = 0 if user.is_authenticated(): conn", "'''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if context is None: # 缓存中没有数据 #", "IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners type.title_banners = title_banners context = {", "IndexGoodsBanner from goods.models import IndexPromotionBanner from goods.models import IndexTypeGoodsBanner class IndexView(View): '''首页''' def", "尝试从缓存获取数据 context = cache.get('index_page_data') if context is None: # 缓存中没有数据 # 获取商品种类信息 types", "'cart_%d'%user.id cart_count = conn.hlen(cart_key) else: cart_count = 0 # 组织上下文 context.update(cart_count=cart_count) return render(request,", "'''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if context is", "IndexView(View): '''首页''' def get(self, request): '''显示首页''' # 尝试从缓存获取数据 context = cache.get('index_page_data') if context", "type.image_banners = image_banners type.title_banners = title_banners context = { 'types': types, 'goods_banners': goods_banners,", "= GoodsType.objects.all() # 获取首页轮播商品信息 goods_banners = IndexGoodsBanner.objects.all().order_by('index') # 获取首页商品促销活动信息 promotin_banners = IndexPromotionBanner.objects.all().order_by('index') #", "IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 获取type种类首页分类商品的文字信息 title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息 type.image_banners = image_banners" ]
[ "160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810", "help=\"increase output verbosity (e.g., -vv is more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP", "file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and html-result files are stored. By", "sys, os, optparse, time from os.path import expanduser PY2 = sys.version_info[0] == 2", "urllib2 import HTTPError,URLError else: from urllib import parse from urllib.request import urlopen, Request", "import HTTPError,URLError from output import Output import json import pprint import random, string", "metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how . default", "200 except HTTPError as e: logger.critical('%s : Can not excecute the HTTP request'", "= time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1]", "COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv is more than", "os.path import expanduser PY2 = sys.version_info[0] == 2 if PY2: from urllib import", "data_string) try: response = urlopen(request) assert response.code == 200 except HTTPError as e:", "- ..... ''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog \"", "f.close() l = 0 for host in lines: if(options.iphost == host.split()[0]): options.auth =", "groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the json module to dump", "apiaction) request = Request(apiaction,data_string) # Creating a group requires an authorization header. request.add_header('Authorization',", "##HEW-T print('Response %s' % response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is True", "assert response_dict[\"success\"] is True # package_create returns the created package as its result.", "dictionary to a string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2", "##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the json module to dump the dictionary", "%s' % apiaction) request = Request(apiaction,data_string) # Creating a group requires an authorization", "is mandatory !') sys.exit() if (not options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')):", "access job host authentification file %s/.netrc ' % home ) sys.exit() else: f", ": Can not excecute the HTTP request' % e) sys.exit(-1) # Use the", "'CreateCommuities.py', version = \"%prog \" + 'v0.1', usage = \"%prog [options] COMMUNITY\" )", "B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API key, by", ") sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for host", "CKAN groups - ..... ''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version =", "0 for host in lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1] break if", "##HEW-T print('group_dict %s' % group_dict) if (True): ##for group_dict in groupsdict.itervalues() : ##HEW-T", "Request from urllib2 import HTTPError,URLError else: from urllib import parse from urllib.request import", "if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification file %s/.netrc ' %", "(CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API key, by default taken", "% options.auth) if options.mode == 'c' : action='group_create' ##elif options.mode == 'u' :", "response.code == 200 except HTTPError as e: logger.critical('%s : Can not excecute the", "random, string p = optparse.OptionParser( description = '''Description =========== Management of B2FIND communities", "(d)elete, (p)urge and (s)how . default is creation of a group', default='c') options,arguments", "e) sys.exit(-1) # Use the json module to load CKAN's response into a", "% response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is True # package_create returns", "as f: group_dict = json.load(f) # checking given options: if (not options.iphost): logger.critical('The", "encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D", "else: from urllib import parse from urllib.request import urlopen, Request from urllib.error import", ": action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported' % options.mode) sys.exit(-1) ##HEW-T", "action that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted : %s'", "import urlopen, Request from urllib2 import HTTPError,URLError else: from urllib import parse from", "for CKAN API (API key, by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory", "print('aaauth %s' % options.auth) if options.mode == 'c' : action='group_create' ##elif options.mode ==", "options.auth = host.split()[1] break if (not options.auth): logger.critical('API key is neither given by", "%s' % options.auth) if options.mode == 'c' : action='group_create' ##elif options.mode == 'u'", "posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ##", "string p = optparse.OptionParser( description = '''Description =========== Management of B2FIND communities within", "-vv is more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal", ", encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that should be excecuted. apiaction='http://%s/api/action/%s' %", "as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch),", "Request from urllib.error import HTTPError,URLError from output import Output import json import pprint", "not excecute the HTTP request' % e) sys.exit(-1) # Use the json module", "that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted : %s' %", "and (s)how . default is creation of a group', default='c') options,arguments = p.parse_args()", "Use the json module to dump the dictionary to a string for posting.", ": data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The", ": action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete' elif options.mode == 'p'", "'d' : action='group_delete' elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode ==", "= json.load(f) # checking given options: if (not options.iphost): logger.critical('The option iphost is", "-v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth',", "for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\")", "# Make the HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string) try: response =", "response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict = json.loads(response_dict) ##", "(patch), (d)elete, (p)urge and (s)how . default is creation of a group', default='c')", ": action='group_delete' elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's'", "2 if PY2: from urllib import quote from urllib2 import urlopen, Request from", "module to dump the dictionary to a string for posting. ### data_string =", "response into a dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T", "EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN groups - ..... ''', formatter =", "CKAN's response into a dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8')", "key is neither given by option --auth nor can retrieved from %s/.netrc' %", "startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete,", "excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted : %s' % apiaction) request =", "of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API key,", "of B2FIND communities within EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN groups -", "from %s/.netrc' % home ) sys.exit() print('aaauth %s' % options.auth) if options.mode ==", "expanduser PY2 = sys.version_info[0] == 2 if PY2: from urllib import quote from", "== 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete' elif options.mode", "action excecuted : %s' % apiaction) request = Request(apiaction,data_string) # Creating a group", "action=\"count\", help=\"increase output verbosity (e.g., -vv is more than -v)\", default=False) p.add_option('--iphost', '-i',", "API (API key, by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log,", "home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification file", "options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT =", "description = '''Description =========== Management of B2FIND communities within EUDAT-B2FIND, comprising - Creating", "data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action", "HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that should be excecuted.", "parse from urllib.request import urlopen, Request from urllib.error import HTTPError,URLError from output import", "options.mode == 'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch' :", "is creation of a group', default='c') options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d", "as e: logger.critical('%s : Can not excecute the HTTP request' % e) sys.exit(-1)", "group', default='c') options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid()", "creation of a group', default='c') options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\")", ": data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else :", "options.iphost): logger.critical('The option iphost is mandatory !') sys.exit() if (not options.auth): home =", "## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that should be", "= '''Description =========== Management of B2FIND communities within EUDAT-B2FIND, comprising - Creating communities,", "group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete' elif options.mode == 'p' : action='group_purge'", "from urllib2 import HTTPError,URLError else: from urllib import parse from urllib.request import urlopen,", "options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name']", "in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the json module to", ": action='group_create' ##elif options.mode == 'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode", "dump the dictionary to a string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8'", "else : logger.critical('Mode %s not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' %", "print('group_dict %s' % group_dict) if (True): ##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n'", "Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r') as f:", "os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification file %s/.netrc ' % home )", "== 200 except HTTPError as e: logger.critical('%s : Can not excecute the HTTP", "help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how . default is", "options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete' elif", "# Use the json module to load CKAN's response into a dictionary. ##", "from urllib import quote from urllib2 import urlopen, Request from urllib2 import HTTPError,URLError", "'--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv is more than -v)\", default=False) p.add_option('--iphost',", "default='c') options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT", "job host authentification file %s/.netrc ' % home ) sys.exit() else: f =", "# Creating a group requires an authorization header. request.add_header('Authorization', options.auth) # Make the", "authorization header. request.add_header('Authorization', options.auth) # Make the HTTP request. ###Py2 response = urllib.request.urlopen(request,", "package_create returns the created package as its result. created_package = response_dict['result'] print('Response:') pprint.pprint(created_package)", "= response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"]", "file %s/.netrc ' % home ) sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close()", "f: group_dict = json.load(f) # checking given options: if (not options.iphost): logger.critical('The option", "(API key, by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error", "options.mode == 'd' : action='group_delete' elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif", "PY2: from urllib import quote from urllib2 import urlopen, Request from urllib2 import", "by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and html-result", "urllib import parse from urllib.request import urlopen, Request from urllib.error import HTTPError,URLError from", "is neither given by option --auth nor can retrieved from %s/.netrc' % home", "The action that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted :", "nor can retrieved from %s/.netrc' % home ) sys.exit() print('aaauth %s' % options.auth)", "the HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert", "options.auth) if options.mode == 'c' : action='group_create' ##elif options.mode == 'u' : ##", "portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API key, by default", "default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and html-result files", "print('group_dict:\\t%s\\n' % (group_dict)) # Use the json module to dump the dictionary to", "%s/.netrc ' % home ) sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l", "directory is created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are", ") sys.exit() print('aaauth %s' % options.auth) if options.mode == 'c' : action='group_create' ##elif", "with open(conffile, 'r') as f: group_dict = json.load(f) # checking given options: if", "where log, error and html-result files are stored. By default directory is created", "excecute the HTTP request' % e) sys.exit(-1) # Use the json module to", "== 'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch'", "'''Description =========== Management of B2FIND communities within EUDAT-B2FIND, comprising - Creating communities, i.e.", "[options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv is more", "else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) #", "\"%prog \" + 'v0.1', usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\",", "optparse, time from os.path import expanduser PY2 = sys.version_info[0] == 2 if PY2:", "request = Request(apiaction,data_string) # Creating a group requires an authorization header. request.add_header('Authorization', options.auth)", "import pprint import random, string p = optparse.OptionParser( description = '''Description =========== Management", "logger.critical('The option iphost is mandatory !') sys.exit() if (not options.auth): home = os.path.expanduser(\"~\")", "authentification file %s/.netrc ' % home ) sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines()", "stored. By default directory is created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE',", "retrieved from %s/.netrc' % home ) sys.exit() print('aaauth %s' % options.auth) if options.mode", "python import sys, os, optparse, time from os.path import expanduser PY2 = sys.version_info[0]", "By default directory is created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported", "(c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how . default is creation of a", "groups - ..... ''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog", "from output import Output import json import pprint import random, string p =", "created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate,", "if options.mode == 'c' : action='group_create' ##elif options.mode == 'u' : ## action='group_update'", "Request(apiaction,data_string) # Creating a group requires an authorization header. request.add_header('Authorization', options.auth) # Make", "request.add_header('Authorization', options.auth) # Make the HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string) try:", "json.loads(response_dict) ## assert response_dict[\"success\"] is True # package_create returns the created package as", "import HTTPError,URLError else: from urllib import parse from urllib.request import urlopen, Request from", "taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and html-result files are", "sys.exit() print('aaauth %s' % options.auth) if options.mode == 'c' : action='group_create' ##elif options.mode", "True # package_create returns the created package as its result. created_package = response_dict['result']", "urllib2 import urlopen, Request from urllib2 import HTTPError,URLError else: from urllib import parse", "(not options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host", "default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification", "= \"%prog \" + 'v0.1', usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose',", "json module to dump the dictionary to a string for posting. ### data_string", "within EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN groups - ..... ''', formatter", "communities within EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN groups - ..... ''',", "HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert response.code", ": action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode", "'v0.1', usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity", "request' % e) sys.exit(-1) # Use the json module to load CKAN's response", "urlopen(request) assert response.code == 200 except HTTPError as e: logger.critical('%s : Can not", "= os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification file %s/.netrc", "from os.path import expanduser PY2 = sys.version_info[0] == 2 if PY2: from urllib", "OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r')", "option iphost is mandatory !') sys.exit() if (not options.auth): home = os.path.expanduser(\"~\") if", "'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete' elif options.mode ==", "the json module to dump the dictionary to a string for posting. ###", "action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete' elif options.mode == 'p' :", "pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options) logger =", "l = 0 for host in lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1]", "(not options.auth): logger.critical('API key is neither given by option --auth nor can retrieved", "###Py2 response = urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert response.code == 200", "to load CKAN's response into a dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict", "= urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert response.code == 200 except HTTPError", "os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile,", "group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not", "metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API key, by default taken from file", "### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D", "response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is", "p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options) logger", "action='group_create' ##elif options.mode == 'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode ==", "more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal (CKAN instance)\",", "f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for host in lines: if(options.iphost", "lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1] break if (not options.auth): logger.critical('API key", "(e.g., -vv is more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND", "= parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that", "be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted : %s' % apiaction) request", "sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for host in", "%H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' %", "## assert response_dict[\"success\"] is True # package_create returns the created package as its", ", encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 ,", "urlopen, Request from urllib.error import HTTPError,URLError from output import Output import json import", "Management of B2FIND communities within EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN groups", "response = urlopen(request) assert response.code == 200 except HTTPError as e: logger.critical('%s :", "supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if (True): ##for group_dict", "))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D", "= os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with", "header. request.add_header('Authorization', options.auth) # Make the HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string)", "is created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate,", "= urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 ,", "help=\"IP adress of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API", "open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for host in lines: if(options.iphost == host.split()[0]):", "should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted : %s' % apiaction)", "== 's' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported' % options.mode)", "HTTPError,URLError else: from urllib import parse from urllib.request import urlopen, Request from urllib.error", "host authentification file %s/.netrc ' % home ) sys.exit() else: f = open(home+'/.netrc','r')", "group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s'", "Make the HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string) try: response = urlopen(request)", "action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict", "'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name']", "if(options.iphost == host.split()[0]): options.auth = host.split()[1] break if (not options.auth): logger.critical('API key is", "os, optparse, time from os.path import expanduser PY2 = sys.version_info[0] == 2 if", "the json module to load CKAN's response into a dictionary. ## print('Response %s'", "to a string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 :", "response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict = json.loads(response_dict) ## assert", "jid = os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community", "print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict", "PY2 = sys.version_info[0] == 2 if PY2: from urllib import quote from urllib2", "quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding)", "Can not excecute the HTTP request' % e) sys.exit(-1) # Use the json", "= host.split()[1] break if (not options.auth): logger.critical('API key is neither given by option", "host.split()[1] break if (not options.auth): logger.critical('API key is neither given by option --auth", "(p)urge and (s)how . default is creation of a group', default='c') options,arguments =", "== 2 if PY2: from urllib import quote from urllib2 import urlopen, Request", "data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810", "##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the json", "and html-result files are stored. By default directory is created as startday/starthour/processid .',", "import json import pprint import random, string p = optparse.OptionParser( description = '''Description", "group requires an authorization header. request.add_header('Authorization', options.auth) # Make the HTTP request. ###Py2", "options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification", "B2FIND communities within EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN groups - .....", "% group_dict) if (True): ##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict))", "encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action)", "Creating a group requires an authorization header. request.add_header('Authorization', options.auth) # Make the HTTP", "if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding)", "p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how", "% e) sys.exit(-1) # Use the json module to load CKAN's response into", ": ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif", "a dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s'", "action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode ==", "given options: if (not options.iphost): logger.critical('The option iphost is mandatory !') sys.exit() if", "error and html-result files are stored. By default directory is created as startday/starthour/processid", "CKAN API (API key, by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where", "help='\\ndirectory where log, error and html-result files are stored. By default directory is", ": ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the json module to dump the", "to dump the dictionary to a string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict))", "home ) sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for", "HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D", "p.add_option('--auth', help=\"Authentification for CKAN API (API key, by default taken from file $HOME/.netrc)\",metavar='STRING')", "= json.loads(response_dict) ## assert response_dict[\"success\"] is True # package_create returns the created package", "checking given options: if (not options.iphost): logger.critical('The option iphost is mandatory !') sys.exit()", "from urllib.request import urlopen, Request from urllib.error import HTTPError,URLError from output import Output", "urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\"", "= optparse.OptionParser( description = '''Description =========== Management of B2FIND communities within EUDAT-B2FIND, comprising", "import urlopen, Request from urllib.error import HTTPError,URLError from output import Output import json", "host in lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1] break if (not options.auth):", "--auth nor can retrieved from %s/.netrc' % home ) sys.exit() print('aaauth %s' %", "## print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict)", "#!/usr/bin/env python import sys, os, optparse, time from os.path import expanduser PY2 =", "p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv is more than -v)\", default=False)", "comprising - Creating communities, i.e. CKAN groups - ..... ''', formatter = optparse.TitledHelpFormatter(),", "p = optparse.OptionParser( description = '''Description =========== Management of B2FIND communities within EUDAT-B2FIND,", "else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for host in lines:", "dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' %", "response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is True # package_create returns the created", "the HTTP request' % e) sys.exit(-1) # Use the json module to load", "from urllib import parse from urllib.request import urlopen, Request from urllib.error import HTTPError,URLError", "than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal (CKAN instance)\", metavar='IP')", "160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that should be excecuted. apiaction='http://%s/api/action/%s'", "default directory is created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes", "json module to load CKAN's response into a dictionary. ## print('Response %s' %", "sys.exit() if (not options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access", "= p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options)", "import sys, os, optparse, time from os.path import expanduser PY2 = sys.version_info[0] ==", ": %s' % apiaction) request = Request(apiaction,data_string) # Creating a group requires an", "))##HEW-D .decode(encoding) # The action that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API", "home ) sys.exit() print('aaauth %s' % options.auth) if options.mode == 'c' : action='group_create'", "p.add_option('--jobdir', help='\\ndirectory where log, error and html-result files are stored. By default directory", "(s)how . default is creation of a group', default='c') options,arguments = p.parse_args() pstat=dict()", "urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert response.code == 200 except HTTPError as", "pprint import random, string p = optparse.OptionParser( description = '''Description =========== Management of", "of a group', default='c') options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid", "community with open(conffile, 'r') as f: group_dict = json.load(f) # checking given options:", "i.e. CKAN groups - ..... ''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version", "modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how . default is creation", ": logger.critical('Mode %s not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict)", "= sys.version_info[0] == 2 if PY2: from urllib import quote from urllib2 import", "iphost is mandatory !') sys.exit() if (not options.auth): home = os.path.expanduser(\"~\") if (not", "option --auth nor can retrieved from %s/.netrc' % home ) sys.exit() print('aaauth %s'", "Creating communities, i.e. CKAN groups - ..... ''', formatter = optparse.TitledHelpFormatter(), prog =", "request. ###Py2 response = urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert response.code ==", "sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if (True): ##for group_dict in groupsdict.itervalues() :", "action='group_delete' elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' :", "version = \"%prog \" + 'v0.1', usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v',", "time from os.path import expanduser PY2 = sys.version_info[0] == 2 if PY2: from", "prog = 'CreateCommuities.py', version = \"%prog \" + 'v0.1', usage = \"%prog [options]", "assert response.code == 200 except HTTPError as e: logger.critical('%s : Can not excecute", "json import pprint import random, string p = optparse.OptionParser( description = '''Description ===========", "= 0 for host in lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1] break", "' % home ) sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l =", "% home ) sys.exit() print('aaauth %s' % options.auth) if options.mode == 'c' :", "= OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r') as f: group_dict =", "HTTP request' % e) sys.exit(-1) # Use the json module to load CKAN's", "os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification file %s/.netrc '", "sys.exit(-1) # Use the json module to load CKAN's response into a dictionary.", "\" + 'v0.1', usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase", "%s not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if (True):", "= 'CreateCommuities.py', version = \"%prog \" + 'v0.1', usage = \"%prog [options] COMMUNITY\"", "try: response = urlopen(request) assert response.code == 200 except HTTPError as e: logger.critical('%s", "group_dict = json.load(f) # checking given options: if (not options.iphost): logger.critical('The option iphost", "lines=f.read().splitlines() f.close() l = 0 for host in lines: if(options.iphost == host.split()[0]): options.auth", "import quote from urllib2 import urlopen, Request from urllib2 import HTTPError,URLError else: from", "default is creation of a group', default='c') options,arguments = p.parse_args() pstat=dict() now =", ".', default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge", "neither given by option --auth nor can retrieved from %s/.netrc' % home )", "%s' % response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is True # package_create", "= Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r') as", "p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for", "by option --auth nor can retrieved from %s/.netrc' % home ) sys.exit() print('aaauth", "parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) # The action that should", "(group_dict)) # Use the json module to dump the dictionary to a string", "urllib.error import HTTPError,URLError from output import Output import json import pprint import random,", "response = urllib.request.urlopen(request, data_string) try: response = urlopen(request) assert response.code == 200 except", "Use the json module to load CKAN's response into a dictionary. ## print('Response", "elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported'", ". default is creation of a group', default='c') options,arguments = p.parse_args() pstat=dict() now", "logger.critical('%s : Can not excecute the HTTP request' % e) sys.exit(-1) # Use", "module to load CKAN's response into a dictionary. ## print('Response %s' % response.read().decode('utf-8'))", "encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\"", "Output import json import pprint import random, string p = optparse.OptionParser( description =", "## group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd'", "logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r') as f: group_dict", "apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted : %s' % apiaction) request = Request(apiaction,data_string)", "'-i', help=\"IP adress of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN", "options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if (True): ##for group_dict in groupsdict.itervalues()", "## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode", "= \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv", ".decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding)", "host.split()[0]): options.auth = host.split()[1] break if (not options.auth): logger.critical('API key is neither given", "% (options.iphost,action) print('API action excecuted : %s' % apiaction) request = Request(apiaction,data_string) #", "== 'c' : action='group_create' ##elif options.mode == 'u' : ## action='group_update' ## group_dict['id']=group_dict['name']", "a string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string", "= quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string =", "HTTPError as e: logger.critical('%s : Can not excecute the HTTP request' % e)", "sys.version_info[0] == 2 if PY2: from urllib import quote from urllib2 import urlopen,", "can retrieved from %s/.netrc' % home ) sys.exit() print('aaauth %s' % options.auth) if", "the dictionary to a string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if", "a group requires an authorization header. request.add_header('Authorization', options.auth) # Make the HTTP request.", "import Output import json import pprint import random, string p = optparse.OptionParser( description", "options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported' %", "community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r') as f: group_dict = json.load(f) #", "% (group_dict)) # Use the json module to dump the dictionary to a", "== 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else", "group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the json module", "# checking given options: if (not options.iphost): logger.critical('The option iphost is mandatory !')", "in lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1] break if (not options.auth): logger.critical('API", ") p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv is more than -v)\",", "elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show'", "(True): ##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use the", "json.load(f) # checking given options: if (not options.iphost): logger.critical('The option iphost is mandatory", "PY2 : data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else", "!') sys.exit() if (not options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not", "%s/.netrc' % home ) sys.exit() print('aaauth %s' % options.auth) if options.mode == 'c'", "if (not options.auth): logger.critical('API key is neither given by option --auth nor can", "%s' % group_dict) if (True): ##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' %", "%s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict =", "output verbosity (e.g., -vv is more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress", "== 'd' : action='group_delete' elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode", "urlopen, Request from urllib2 import HTTPError,URLError else: from urllib import parse from urllib.request", "% response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response %s' % response_dict) response_dict = json.loads(response_dict)", "% home ) sys.exit() else: f = open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0", "response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is True # package_create returns the", "import parse from urllib.request import urlopen, Request from urllib.error import HTTPError,URLError from output", "HTTPError,URLError from output import Output import json import pprint import random, string p", "verbosity (e.g., -vv is more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of", "is more than -v)\", default=False) p.add_option('--iphost', '-i', help=\"IP adress of B2FIND portal (CKAN", "if (not options.iphost): logger.critical('The option iphost is mandatory !') sys.exit() if (not options.auth):", "= urlopen(request) assert response.code == 200 except HTTPError as e: logger.critical('%s : Can", "if PY2: from urllib import quote from urllib2 import urlopen, Request from urllib2", "except HTTPError as e: logger.critical('%s : Can not excecute the HTTP request' %", "'c' : action='group_create' ##elif options.mode == 'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif", "$HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and html-result files are stored. By default", "'-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how .", "elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' : action='group_delete'", "## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string = parse.quote(json.dumps(group_dict)).encode(encoding) ##", "instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API key, by default taken from", "import expanduser PY2 = sys.version_info[0] == 2 if PY2: from urllib import quote", "not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if (True): ##for", "if (True): ##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) # Use", "formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog \" + 'v0.1', usage", "# The action that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action excecuted", "% apiaction) request = Request(apiaction,data_string) # Creating a group requires an authorization header.", "is True # package_create returns the created package as its result. created_package =", "'s' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s not supported' % options.mode) sys.exit(-1)", "##elif options.mode == 'u' : ## action='group_update' ## group_dict['id']=group_dict['name'] elif options.mode == 'patch'", "help=\"Authentification for CKAN API (API key, by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir',", "output import Output import json import pprint import random, string p = optparse.OptionParser(", "options: if (not options.iphost): logger.critical('The option iphost is mandatory !') sys.exit() if (not", "=========== Management of B2FIND communities within EUDAT-B2FIND, comprising - Creating communities, i.e. CKAN", "string for posting. ### data_string = urllib.parse.quote(json.dumps(dataset_dict)) encoding='utf-8' if PY2 : data_string =", "key, by default taken from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and", "open(conffile, 'r') as f: group_dict = json.load(f) # checking given options: if (not", "OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json' % community with open(conffile, 'r') as f: group_dict = json.load(f)", "(not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job host authentification file %s/.netrc ' % home", "a group', default='c') options,arguments = p.parse_args() pstat=dict() now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid =", "optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog \" + 'v0.1', usage = \"%prog", "\"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g., -vv is", "elif options.mode == 'd' : action='group_delete' elif options.mode == 'p' : action='group_purge' group_dict['id']=group_dict['name']", "into a dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict = response.read().decode('utf-8') ##HEW-T print('Response", "conffile='mapfiles/%s.json' % community with open(conffile, 'r') as f: group_dict = json.load(f) # checking", "urllib.request import urlopen, Request from urllib.error import HTTPError,URLError from output import Output import", "options.mode == 'c' : action='group_create' ##elif options.mode == 'u' : ## action='group_update' ##", "(u)pdate, (patch), (d)elete, (p)urge and (s)how . default is creation of a group',", "% community with open(conffile, 'r') as f: group_dict = json.load(f) # checking given", "logger.critical('Mode %s not supported' % options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if", "are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and (s)how . default is creation of", "== host.split()[0]): options.auth = host.split()[1] break if (not options.auth): logger.critical('API key is neither", "= optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog \" + 'v0.1', usage =", "break if (not options.auth): logger.critical('API key is neither given by option --auth nor", "not access job host authentification file %s/.netrc ' % home ) sys.exit() else:", "response_dict[\"success\"] is True # package_create returns the created package as its result. created_package", "optparse.OptionParser( description = '''Description =========== Management of B2FIND communities within EUDAT-B2FIND, comprising -", "'p' : action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else :", "# package_create returns the created package as its result. created_package = response_dict['result'] print('Response:')", "log, error and html-result files are stored. By default directory is created as", "..... ''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog \" +", "(options.iphost,action) print('API action excecuted : %s' % apiaction) request = Request(apiaction,data_string) # Creating", "excecuted : %s' % apiaction) request = Request(apiaction,data_string) # Creating a group requires", "usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output verbosity (e.g.,", "print('Response %s' % response_dict) response_dict = json.loads(response_dict) ## assert response_dict[\"success\"] is True #", "communities, i.e. CKAN groups - ..... ''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py',", "requires an authorization header. request.add_header('Authorization', options.auth) # Make the HTTP request. ###Py2 response", "print('API action excecuted : %s' % apiaction) request = Request(apiaction,data_string) # Creating a", "''', formatter = optparse.TitledHelpFormatter(), prog = 'CreateCommuities.py', version = \"%prog \" + 'v0.1',", "from file $HOME/.netrc)\",metavar='STRING') p.add_option('--jobdir', help='\\ndirectory where log, error and html-result files are stored.", "urllib import quote from urllib2 import urlopen, Request from urllib2 import HTTPError,URLError else:", "- Creating communities, i.e. CKAN groups - ..... ''', formatter = optparse.TitledHelpFormatter(), prog", "default=None) p.add_option('--mode', '-m', metavar='PROCESSINGMODE', help='\\nSupported modes are (c)reate, (u)pdate, (patch), (d)elete, (p)urge and", "options.auth) # Make the HTTP request. ###Py2 response = urllib.request.urlopen(request, data_string) try: response", "quote from urllib2 import urlopen, Request from urllib2 import HTTPError,URLError else: from urllib", "time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose) community=sys.argv[1] conffile='mapfiles/%s.json'", "now = time.strftime(\"%Y-%m-%d %H:%M:%S\") jid = os.getpid() OUT = Output(pstat,now,jid,options) logger = OUT.setup_custom_logger('root',options.verbose)", "for host in lines: if(options.iphost == host.split()[0]): options.auth = host.split()[1] break if (not", "an authorization header. request.add_header('Authorization', options.auth) # Make the HTTP request. ###Py2 response =", "= Request(apiaction,data_string) # Creating a group requires an authorization header. request.add_header('Authorization', options.auth) #", "data_string = quote(json.dumps(group_dict))##.encode(\"utf-8\") ## HEW-D 160810 , encoding=\"latin-1\" ))##HEW-D .decode(encoding) else : data_string", "files are stored. By default directory is created as startday/starthour/processid .', default=None) p.add_option('--mode',", "are stored. By default directory is created as startday/starthour/processid .', default=None) p.add_option('--mode', '-m',", "'r') as f: group_dict = json.load(f) # checking given options: if (not options.iphost):", "e: logger.critical('%s : Can not excecute the HTTP request' % e) sys.exit(-1) #", "load CKAN's response into a dictionary. ## print('Response %s' % response.read().decode('utf-8')) response_dict =", "% options.mode) sys.exit(-1) ##HEW-T print('group_dict %s' % group_dict) if (True): ##for group_dict in", "logger.critical('API key is neither given by option --auth nor can retrieved from %s/.netrc'", "html-result files are stored. By default directory is created as startday/starthour/processid .', default=None)", "(not options.iphost): logger.critical('The option iphost is mandatory !') sys.exit() if (not options.auth): home", "mandatory !') sys.exit() if (not options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can", "group_dict) if (True): ##for group_dict in groupsdict.itervalues() : ##HEW-T print('group_dict:\\t%s\\n' % (group_dict)) #", "from urllib2 import urlopen, Request from urllib2 import HTTPError,URLError else: from urllib import", "+ 'v0.1', usage = \"%prog [options] COMMUNITY\" ) p.add_option('-v', '--verbose', action=\"count\", help=\"increase output", "logger.critical('Can not access job host authentification file %s/.netrc ' % home ) sys.exit()", "action='group_purge' group_dict['id']=group_dict['name'] elif options.mode == 's' : action='group_show' group_dict['id']=group_dict['name'] else : logger.critical('Mode %s", "import random, string p = optparse.OptionParser( description = '''Description =========== Management of B2FIND", "options.auth): logger.critical('API key is neither given by option --auth nor can retrieved from", "# Use the json module to dump the dictionary to a string for", "group_dict['id']=group_dict['name'] elif options.mode == 'patch' : action='group_patch' group_dict['id']=group_dict['name'] elif options.mode == 'd' :", "if (not options.auth): home = os.path.expanduser(\"~\") if (not os.path.isfile(home+'/.netrc')): logger.critical('Can not access job", ".decode(encoding) # The action that should be excecuted. apiaction='http://%s/api/action/%s' % (options.iphost,action) print('API action", "given by option --auth nor can retrieved from %s/.netrc' % home ) sys.exit()", "from urllib.error import HTTPError,URLError from output import Output import json import pprint import", "adress of B2FIND portal (CKAN instance)\", metavar='IP') p.add_option('--auth', help=\"Authentification for CKAN API (API", "= open(home+'/.netrc','r') lines=f.read().splitlines() f.close() l = 0 for host in lines: if(options.iphost ==" ]
[ "3 Programming/ex_5_8.py import turtle import math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle()", "wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50)", "Programming/ex_5_8.py import turtle import math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90)", "in range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50 / 2) bob.forward(distance) bob.right(90) bob.forward(distance)", "turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50 /", "for _ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50 / 2) bob.forward(distance)", "import turtle import math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for", "= turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50", "import math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _ in", "<reponame>ElizaLo/Practice-Python<filename>Python 3 Programming/ex_5_8.py import turtle import math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob =", "turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50) bob.left(90) bob.right(225)", "math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _ in range(4):", "range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50 / 2) bob.forward(distance) bob.right(90) bob.forward(distance) wn.exitonclick()", "turtle import math wn = turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _", "wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance", "bob = turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance =", "_ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50 / 2) bob.forward(distance) bob.right(90)", "bob.right(90) for _ in range(4): bob.forward(50) bob.left(90) bob.right(225) distance = math.sqrt(50*50 / 2)", "= turtle.Screen() wn.bgcolor(\"SkyBlue\") bob = turtle.Turtle() bob.right(90) for _ in range(4): bob.forward(50) bob.left(90)" ]
[ "os import glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs =", "len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs = sys.argv[1:] for dir in", "sys.argv[1:] for dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython", "for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert --to rst {0}'.format(notebook) print(cmd)", "for dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert", "import sys import os import glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()]", "dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert --to", "dirs = sys.argv[1:] for dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd", "sys import os import glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else:", "0: dirs = [os.getcwd()] else: dirs = sys.argv[1:] for dir in dirs: for", "= [os.getcwd()] else: dirs = sys.argv[1:] for dir in dirs: for notebook in", "import glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs = sys.argv[1:]", "glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs = sys.argv[1:] for", "= sys.argv[1:] for dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd =", "[os.getcwd()] else: dirs = sys.argv[1:] for dir in dirs: for notebook in glob.glob(os.path.join(dir,", "in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert --to rst", "#!/usr/bin/env python3 import sys import os import glob if len(sys.argv[1:]) == 0: dirs", "dirs = [os.getcwd()] else: dirs = sys.argv[1:] for dir in dirs: for notebook", "== 0: dirs = [os.getcwd()] else: dirs = sys.argv[1:] for dir in dirs:", "notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert --to rst {0}'.format(notebook) print(cmd) os.system(cmd)", "dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert --to rst {0}'.format(notebook)", "python3 import sys import os import glob if len(sys.argv[1:]) == 0: dirs =", "if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs = sys.argv[1:] for dir", "import os import glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs", "else: dirs = sys.argv[1:] for dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')):" ]
[ "u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return info", "\"name\" : self.name, \"gender\" : self.gender, \"address\" : self.address, \"role\" : self.role, \"score\"", "taskdata = 0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count()", "datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod def login(loginid,", "address, birth, cellphone): if password.strip() != \"\": self.password = generate_password_hash(password) self.name = name", "p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return info def setStatus(self,status):", "import datetime import random from werkzeug.security import generate_password_hash, check_password_hash enrollcode = { \"Waiting\"", "= True, nullable = False) loginid = Column(Unicode(100), unique = True, nullable =", "def setScore(self): sums = list() for en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid", "ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return info def setStatus(self,status): self.status =", "Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name = name self.password", "self.dict() submitinfo = dict(parsed = 0, taskdata = 0) for en in self.enrolls:", "editInfo(self, name, password, gender, address, birth, cellphone): if password.strip() != \"\": self.password =", "id = Column(Integer, primary_key=True, autoincrement = True, nullable = False) loginid = Column(Unicode(100),", "session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps: for t in p.tasks: session.delete(t) session.delete(p)", "= cellphone session.add(user) session.commit() @staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first()", "submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for", "session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all()", "True, nullable = False) loginid = Column(Unicode(100), unique = True, nullable = False)", "check_password_hash(self.password, password) def dict(self): tslist = [] for x in self.enrolls: x.task.setTables() ts", "dict(parsed = 0, taskdata = 0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] +=", "en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid ==", "False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default = u\"남자\") address =", "self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone = cellphone session.commit() def setScore(self):", "ForeignKey('Task.prefix'), nullable = False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable = False) status", "tslist = [] for x in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] =", "label from sqlalchemy.orm import relationship from sqlalchemy.sql import func from datetime import datetime", "False , server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ =", "__tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable =", "__tablename__ = 'User' id = Column(Integer, primary_key=True, autoincrement = True, nullable = False)", "Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name = name self.password = generate_password_hash(password) def", "password, name, gender, address , role, birth,cellphone): user = User(loginid, name, password) user.gender", "password, gender, address, birth, cellphone): if password.strip() != \"\": self.password = generate_password_hash(password) self.name", "= list() for enroll in self.enrolls: task = enroll.task.dict() if task[\"status\"] == \"Stop\":", "= name self.gender = gender self.address = address self.birth = datetime.strptime(birth, \"%a %b", "autoincrement = True, nullable = False) loginid = Column(Unicode(100), unique = True, nullable", "class Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'),", "return check_password_hash(self.password, password) def dict(self): tslist = [] for x in self.enrolls: x.task.setTables()", "+= len(p.tasks) info[\"submitinfo\"] = submitinfo return info def setStatus(self,status): self.status = status session.commit()", "u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def getUsers():", "user.address = address user.role = role user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date()", "self.status = status session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if", "x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id,", "if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status]", "self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist = []", "relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User' id = Column(Integer, primary_key=True, autoincrement =", "= x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" :", "list() for enroll in self.enrolls: task = enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"]", "= Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name = name", "\"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"] :", "%d %Y\").date() self.cellphone = cellphone session.commit() def setScore(self): sums = list() for en", "datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone = cellphone session.commit() def setScore(self): sums =", "relationship from sqlalchemy.sql import func from datetime import datetime import random from werkzeug.security", "self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"] : data[\"birthstring\"] =", ": self.role, \"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\" :", "= Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default", "== 0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id):", "in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps: for", "x in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self)", "} if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls =", "ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed", "datetime import random from werkzeug.security import generate_password_hash, check_password_hash enrollcode = { \"Waiting\" :", "= u\"제출자\") score = Column(Integer, server_default = \"0\", nullable = False) birth =", "\"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인 거절\", }", "= False) name = Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable", ": self.id, \"loginid\" : self.loginid, \"name\" : self.name, \"gender\" : self.gender, \"address\" :", "= u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False,", "for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid", "def deleteUser(user): for en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for", "backref=\"enrolls\") class User(Base): __tablename__ = 'User' id = Column(Integer, primary_key=True, autoincrement = True,", "en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p", "def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist = [] for x in", "sqlalchemy import Column, Integer, Unicode, Enum, Date, String from sqlalchemy import Table, ForeignKey,", "in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return info def setStatus(self,status): self.status", ": tslist } if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self):", "== self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def", "\"address\" : self.address, \"role\" : self.role, \"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\"", "\"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist }", "deleteUser(user): for en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p", "\"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User' id = Column(Integer,", "session.commit() def setScore(self): sums = list() for en in self.enrolls: en.task.setTables() ps =", "User(Base): __tablename__ = 'User' id = Column(Integer, primary_key=True, autoincrement = True, nullable =", "return enrolls def editInfo(self, name, password, gender, address, birth, cellphone): if password.strip() !=", "user = session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password) : return user else", "Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default =", ": return user else : return None @staticmethod def deleteUser(user): for en in", "else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name, password, gender,", "= False) birth = Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid", "en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: sums.append(p.score)", "cellphone session.add(user) session.commit() @staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first() if", "= \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User' id =", "name, password) user.gender = gender user.address = address user.role = role user.birth =", "def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role", "ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id, \"loginid\"", ": self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist } if", "= self.dict() submitinfo = dict(parsed = 0, taskdata = 0) for en in", "def setStatus(self,status): self.status = status session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role ==", "session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod", "+= session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p", "return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id)", "Unicode, Enum, Date, String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import", "@staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender, address ,", "@staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password)", "for p in ps: for t in p.tasks: session.delete(t) session.delete(p) for e in", "session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"]", "= False , server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__", "user else : return None @staticmethod def deleteUser(user): for en in user.enrolls: en.task.setTables()", "session.add(user) session.commit() @staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first() if user", "False, server_default = u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable", "login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password) : return", "{\"id\" : self.id, \"loginid\" : self.loginid, \"name\" : self.name, \"gender\" : self.gender, \"address\"", "= False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default = u\"남자\") address", "in ps: for t in p.tasks: session.delete(t) session.delete(p) for e in user.enrolls :", "self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps:", "u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)]", "Column(String(100), nullable = False) name = Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\",", "u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def", "__init__(self,loginid,name,password): self.loginid = loginid self.name = name self.password = generate_password_hash(password) def checkPassword(self,password): return", "address self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone = cellphone session.commit() def", "return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return", "nullable = False) name = Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"),", "getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name,", "= Column(Integer, server_default = \"0\", nullable = False) birth = Column(Date) cellphone =", "loginid).first() if user and user.checkPassword(password) : return user else : return None @staticmethod", "userid = Column('userid', Integer, ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable =", "\"tasks\" : tslist } if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def", "t in p.tasks: session.delete(t) session.delete(p) for e in user.enrolls : session.delete(e) session.delete(user) session.commit()", "= role user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone = cellphone session.add(user)", "= {\"id\" : self.id, \"loginid\" : self.loginid, \"name\" : self.name, \"gender\" : self.gender,", "task = enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\" else :", "= gender user.address = address user.role = role user.birth = datetime.strptime(birth, \"%a %b", "True, nullable = False) password = Column(String(100), nullable = False) name = Column(Unicode(100),", "= generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist = [] for", "for p in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict()", "import func from datetime import datetime import random from werkzeug.security import generate_password_hash, check_password_hash", "for x in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] =", "ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id, \"loginid\" : self.loginid, \"name\"", "= 0, taskdata = 0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid", "\"cellphone\" : self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat()", "self.loginid = loginid self.name = name self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password,", "return user else : return None @staticmethod def deleteUser(user): for en in user.enrolls:", "def dict(self): tslist = [] for x in self.enrolls: x.task.setTables() ts = x.task.dict()", "primary_key=True, autoincrement = True, nullable = False) loginid = Column(Unicode(100), unique = True,", "for t in p.tasks: session.delete(t) session.delete(p) for e in user.enrolls : session.delete(e) session.delete(user)", "= status session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum", "u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name,", "'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid", "Column('userid', Integer, ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False ,", "en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all()", "= Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default = u\"남자\") address = Column(Unicode(255)) role", "loginid = Column(Unicode(100), unique = True, nullable = False) password = Column(String(100), nullable", "Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable = False)", "= False) password = Column(String(100), nullable = False) name = Column(Unicode(100), nullable =", "= address self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone = cellphone session.commit()", "== u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role ==", "self.id, \"loginid\" : self.loginid, \"name\" : self.name, \"gender\" : self.gender, \"address\" : self.address,", "= datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone = cellphone session.commit() def setScore(self): sums", "def getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed = 0, taskdata = 0)", "__table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid =", "user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User' id = Column(Integer, primary_key=True,", "return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender,", "in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts)", "password.strip() != \"\": self.password = generate_password_hash(password) self.name = name self.gender = gender self.address", "= \"0\", nullable = False) birth = Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password):", "False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default = \"Waiting\") user =", "session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in", "server_default = u\"제출자\") score = Column(Integer, server_default = \"0\", nullable = False) birth", "nullable = False , server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base):", "user.cellphone = cellphone session.add(user) session.commit() @staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid ==", "maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def", "'User' id = Column(Integer, primary_key=True, autoincrement = True, nullable = False) loginid =", "@staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid,", "False) password = Column(String(100), nullable = False) name = Column(Unicode(100), nullable = False)", "name = Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False,", "enrolls = list() for enroll in self.enrolls: task = enroll.task.dict() if task[\"status\"] ==", "password) def dict(self): tslist = [] for x in self.enrolls: x.task.setTables() ts =", "import relationship from sqlalchemy.sql import func from datetime import datetime import random from", "\"0\", nullable = False) birth = Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid", "= session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first() return", "newUser(loginid, password, name, gender, address , role, birth,cellphone): user = User(loginid, name, password)", "= submitinfo return info def setStatus(self,status): self.status = status session.commit() @staticmethod def randomEvaluator():", "role user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone = cellphone session.add(user) session.commit()", "getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender, address , role, birth,cellphone):", "\"\": self.password = generate_password_hash(password) self.name = name self.gender = gender self.address = address", "generate_password_hash(password) self.name = name self.gender = gender self.address = address self.birth = datetime.strptime(birth,", "from sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship from sqlalchemy.sql import func from", "= enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name, password, gender, address, birth, cellphone):", "gender user.address = address user.role = role user.birth = datetime.strptime(birth, \"%a %b %d", "= 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False)", "import label from sqlalchemy.orm import relationship from sqlalchemy.sql import func from datetime import", "== self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] =", "class User(Base): __tablename__ = 'User' id = Column(Integer, primary_key=True, autoincrement = True, nullable", "session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender, address , role, birth,cellphone): user =", "enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name, password, gender, address, birth, cellphone): if", "nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default = u\"남자\")", "session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role", "submitinfo = dict(parsed = 0, taskdata = 0) for en in self.enrolls: en.task.setTables()", "False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable", "(PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid = Column('userid', Integer,", "session.commit() @staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first() if user and", "enroll in self.enrolls: task = enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집", "data def enrollStatus(self): enrolls = list() for enroll in self.enrolls: task = enroll.task.dict()", "self.name = name self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self):", "== u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info", "unique = True, nullable = False) password = Column(String(100), nullable = False) name", "def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender, address , role,", "len(p.tasks) info[\"submitinfo\"] = submitinfo return info def setStatus(self,status): self.status = status session.commit() @staticmethod", "check_password_hash enrollcode = { \"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\"", "= loginid self.name = name self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password)", "종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name, password,", ": task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name, password, gender, address,", "data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls = list() for enroll in", "nullable = False) loginid = Column(Unicode(100), unique = True, nullable = False) password", "from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm import", "enrolls.append(task) return enrolls def editInfo(self, name, password, gender, address, birth, cellphone): if password.strip()", "= False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default = \"Waiting\") user", "coding: utf-8 -*- from DBP.models import Base,session from sqlalchemy import Column, Integer, Unicode,", "False, server_default = u\"제출자\") score = Column(Integer, server_default = \"0\", nullable = False)", "in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo =", "= True, nullable = False) password = Column(String(100), nullable = False) name =", "info = self.dict() submitinfo = dict(parsed = 0, taskdata = 0) for en", "in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in", "= data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls = list() for enroll in self.enrolls:", "session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score = sum(sums)/len(sums)", "info[\"submitinfo\"] = submitinfo return info def setStatus(self,status): self.status = status session.commit() @staticmethod def", "cellphone session.commit() def setScore(self): sums = list() for en in self.enrolls: en.task.setTables() ps", "dict(self): tslist = [] for x in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"]", "enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\" else : task[\"status\"] =", "x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id, \"loginid\" : self.loginid, \"name\" : self.name,", "user.id).all() for p in ps: for t in p.tasks: session.delete(t) session.delete(p) for e", "\"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인 거절\", } class Enroll(Base): __tablename__ =", "for en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in", "import Column, Integer, Unicode, Enum, Date, String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint", "= [] for x in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self)", "from datetime import datetime import random from werkzeug.security import generate_password_hash, check_password_hash enrollcode =", "ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default =", "= enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\" else : task[\"status\"]", "self.gender = gender self.address = address self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date()", "Column, Integer, Unicode, Enum, Date, String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from", "cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name = name self.password =", "checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist = [] for x in self.enrolls:", "nullable = False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable = False) status =", "import Base,session from sqlalchemy import Column, Integer, Unicode, Enum, Date, String from sqlalchemy", "for en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for", "{ \"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인 거절\",", "u\"승인 완료\", \"Refused\" : u\"승인 거절\", } class Enroll(Base): __tablename__ = 'Enroll' __table_args__", "if password.strip() != \"\": self.password = generate_password_hash(password) self.name = name self.gender = gender", "self.loginid, \"name\" : self.name, \"gender\" : self.gender, \"address\" : self.address, \"role\" : self.role,", "= Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\")", "= session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score =", "Date, String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from", "enrollStatus(self): enrolls = list() for enroll in self.enrolls: task = enroll.task.dict() if task[\"status\"]", "self.address, \"role\" : self.role, \"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone,", "0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps =", "nullable = False, server_default = u\"제출자\") score = Column(Integer, server_default = \"0\", nullable", "sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship from sqlalchemy.sql import func from datetime", "gender, address, birth, cellphone): if password.strip() != \"\": self.password = generate_password_hash(password) self.name =", "server_default = \"0\", nullable = False) birth = Column(Date) cellphone = Column(Unicode(15)) def", "self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo", "= dict(parsed = 0, taskdata = 0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"]", "-*- from DBP.models import Base,session from sqlalchemy import Column, Integer, Unicode, Enum, Date,", "#-*- coding: utf-8 -*- from DBP.models import Base,session from sqlalchemy import Column, Integer,", "for enroll in self.enrolls: task = enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] =", "if maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod", "taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid = Column('userid', Integer, ForeignKey('User.id'),", "sums = list() for en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status", "info def setStatus(self,status): self.status = status session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role", "def getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password,", "= User(loginid, name, password) user.gender = gender user.address = address user.role = role", "self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data", "name self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist =", "return data def enrollStatus(self): enrolls = list() for enroll in self.enrolls: task =", ": self.gender, \"address\" : self.address, \"role\" : self.role, \"score\" : self.score, \"birthstring\" :", "nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default = \"Waiting\")", "= session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password) : return user else :", "if user and user.checkPassword(password) : return user else : return None @staticmethod def", "%Y\").date() self.cellphone = cellphone session.commit() def setScore(self): sums = list() for en in", ": u\"승인 완료\", \"Refused\" : u\"승인 거절\", } class Enroll(Base): __tablename__ = 'Enroll'", "u\"여자\"), nullable = False, server_default = u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\",", "= False) loginid = Column(Unicode(100), unique = True, nullable = False) password =", "== u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return", "birth, cellphone): if password.strip() != \"\": self.password = generate_password_hash(password) self.name = name self.gender", "%b %d %Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod def login(loginid, password): user", "= Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default = u\"제출자\")", "self.role, \"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist", "ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score", "= Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default = u\"제출자\") score = Column(Integer,", "== u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod", "gender, address , role, birth,cellphone): user = User(loginid, name, password) user.gender = gender", "self.gender, \"address\" : self.address, \"role\" : self.role, \"score\" : self.score, \"birthstring\" : self.birth,", "name, password, gender, address, birth, cellphone): if password.strip() != \"\": self.password = generate_password_hash(password)", "address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default =", ": self.name, \"gender\" : self.gender, \"address\" : self.address, \"role\" : self.role, \"score\" :", "= False, server_default = u\"제출자\") score = Column(Integer, server_default = \"0\", nullable =", "완료\", \"Refused\" : u\"승인 거절\", } class Enroll(Base): __tablename__ = 'Enroll' __table_args__ =", "self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data", "task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self, name, password, gender, address, birth,", "= sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed = 0, taskdata", "Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default = u\"제출자\") score = Column(Integer, server_default", "\"Stop\": task[\"status\"] = u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls", "self.name = name self.gender = gender self.address = address self.birth = datetime.strptime(birth, \"%a", "\"%a %b %d %Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod def login(loginid, password):", "@staticmethod def newUser(loginid, password, name, gender, address , role, birth,cellphone): user = User(loginid,", "self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self):", "= Column(Unicode(100), unique = True, nullable = False) password = Column(String(100), nullable =", "gender self.address = address self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone =", "self.address = address self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone = cellphone", "import generate_password_hash, check_password_hash enrollcode = { \"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인", "u\"Evaluated\").all() for p in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info =", "Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable", "name self.gender = gender self.address = address self.birth = datetime.strptime(birth, \"%a %b %d", "x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data =", "import random from werkzeug.security import generate_password_hash, check_password_hash enrollcode = { \"Waiting\" : u\"승인", "generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist = [] for x", "in self.enrolls: task = enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\"", "= 'User' id = Column(Integer, primary_key=True, autoincrement = True, nullable = False) loginid", "def newUser(loginid, password, name, gender, address , role, birth,cellphone): user = User(loginid, name,", "False) loginid = Column(Unicode(100), unique = True, nullable = False) password = Column(String(100),", "Column(Integer, primary_key=True, autoincrement = True, nullable = False) loginid = Column(Unicode(100), unique =", "= address user.role = role user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone", "\"loginid\" : self.loginid, \"name\" : self.name, \"gender\" : self.gender, \"address\" : self.address, \"role\"", "ps: for t in p.tasks: session.delete(t) session.delete(p) for e in user.enrolls : session.delete(e)", "datetime import datetime import random from werkzeug.security import generate_password_hash, check_password_hash enrollcode = {", "p in ps: sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo", "address , role, birth,cellphone): user = User(loginid, name, password) user.gender = gender user.address", "session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0:", "birth = Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name =", "= { \"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인", "werkzeug.security import generate_password_hash, check_password_hash enrollcode = { \"Waiting\" : u\"승인 대기중\", \"Approved\" :", "\"Refused\" : u\"승인 거절\", } class Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),)", "= gender self.address = address self.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() self.cellphone", "setStatus(self,status): self.status = status session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count()", "task[\"status\"] = u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def", "user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod", ", server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User'", "u\"승인 거절\", } class Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix =", "from werkzeug.security import generate_password_hash, check_password_hash enrollcode = { \"Waiting\" : u\"승인 대기중\", \"Approved\"", "= relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User' id = Column(Integer, primary_key=True, autoincrement", "= generate_password_hash(password) self.name = name self.gender = gender self.address = address self.birth =", "Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class", "name, gender, address , role, birth,cellphone): user = User(loginid, name, password) user.gender =", "= Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable", ", role, birth,cellphone): user = User(loginid, name, password) user.gender = gender user.address =", "= 0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps", "from sqlalchemy import Column, Integer, Unicode, Enum, Date, String from sqlalchemy import Table,", "for p in ps: submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return info def", "user.role = role user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone = cellphone", "random from werkzeug.security import generate_password_hash, check_password_hash enrollcode = { \"Waiting\" : u\"승인 대기중\",", "def login(loginid, password): user = session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password) :", "= Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name = name self.password = generate_password_hash(password)", "tslist.append(ts) data = {\"id\" : self.id, \"loginid\" : self.loginid, \"name\" : self.name, \"gender\"", "== loginid).first() if user and user.checkPassword(password) : return user else : return None", "@staticmethod def deleteUser(user): for en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all()", "from DBP.models import Base,session from sqlalchemy import Column, Integer, Unicode, Enum, Date, String", "u\"평가자\"), nullable = False, server_default = u\"제출자\") score = Column(Integer, server_default = \"0\",", "cellphone): if password.strip() != \"\": self.password = generate_password_hash(password) self.name = name self.gender =", "import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship from", "= session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] += len(p.tasks)", "nullable = False, server_default = u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\",", "def editInfo(self, name, password, gender, address, birth, cellphone): if password.strip() != \"\": self.password", "p in ps: for t in p.tasks: session.delete(t) session.delete(p) for e in user.enrolls", "None @staticmethod def deleteUser(user): for en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid ==", "else : return None @staticmethod def deleteUser(user): for en in user.enrolls: en.task.setTables() ps", "User(loginid, name, password) user.gender = gender user.address = address user.role = role user.birth", "return None @staticmethod def deleteUser(user): for en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid", "ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\"", "= datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod def", ": data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls = list() for enroll", "Integer, ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default", "String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm", "score = Column(Integer, server_default = \"0\", nullable = False) birth = Column(Date) cellphone", "submitinfo[\"taskdata\"] += len(p.tasks) info[\"submitinfo\"] = submitinfo return info def setStatus(self,status): self.status = status", "False) name = Column(Unicode(100), nullable = False) gender = Column(Enum(u\"남자\", u\"여자\"), nullable =", "in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status", "role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default = u\"제출자\") score =", "en in user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps:", "Base,session from sqlalchemy import Column, Integer, Unicode, Enum, Date, String from sqlalchemy import", "= x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id, \"loginid\" : self.loginid, \"name\" :", "tslist } if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls", "거절\", } class Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix',", "return info def setStatus(self,status): self.status = status session.commit() @staticmethod def randomEvaluator(): maxnum =", "data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls = list() for", "sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship", "!= \"\": self.password = generate_password_hash(password) self.name = name self.gender = gender self.address =", "data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls = list() for enroll in self.enrolls: task", "%d %Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod def login(loginid, password): user =", "user.checkPassword(password) : return user else : return None @staticmethod def deleteUser(user): for en", "== self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps:", ": self.address, \"role\" : self.role, \"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\" :", "%Y\").date() user.cellphone = cellphone session.add(user) session.commit() @staticmethod def login(loginid, password): user = session.query(User).filter(User.loginid", ": u\"승인 거절\", } class Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix", "role, birth,cellphone): user = User(loginid, name, password) user.gender = gender user.address = address", "= False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"),", "u\"제출자\", u\"평가자\"), nullable = False, server_default = u\"제출자\") score = Column(Integer, server_default =", "maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role == u\"관리자\").first()", "from sqlalchemy.orm import relationship from sqlalchemy.sql import func from datetime import datetime import", "u\"제출자\") score = Column(Integer, server_default = \"0\", nullable = False) birth = Column(Date)", "nullable = False) birth = Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid =", "} class Enroll(Base): __tablename__ = 'Enroll' __table_args__ = (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100),", "sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed = 0, taskdata =", "return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender, address , role, birth,cellphone): user", ": self.loginid, \"name\" : self.name, \"gender\" : self.gender, \"address\" : self.address, \"role\" :", "ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"] +=", "self.score = sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed = 0,", "self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all() for p in ps: submitinfo[\"taskdata\"]", "= session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps: for t in p.tasks: session.delete(t)", "enrolls def editInfo(self, name, password, gender, address, birth, cellphone): if password.strip() != \"\":", "data = {\"id\" : self.id, \"loginid\" : self.loginid, \"name\" : self.name, \"gender\" :", "sums.append(p.score) self.score = sum(sums)/len(sums) def getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed =", "server_default = u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable =", "Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid = Column('userid', Integer, ForeignKey('User.id'), nullable =", "user and user.checkPassword(password) : return user else : return None @staticmethod def deleteUser(user):", "u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인 거절\", } class Enroll(Base):", "setScore(self): sums = list() for en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid ==", "def __init__(self,loginid,name,password): self.loginid = loginid self.name = name self.password = generate_password_hash(password) def checkPassword(self,password):", "self.enrolls: task = enroll.task.dict() if task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\" else", "@staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0: return", "password): user = session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password) : return user", "PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship from sqlalchemy.sql import func", "Column(Unicode(100), unique = True, nullable = False) password = Column(String(100), nullable = False)", "enrollcode = { \"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" :", "server_default = \"Waiting\") user = relationship(\"User\", backref=\"enrolls\") class User(Base): __tablename__ = 'User' id", "Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship from sqlalchemy.sql", ": self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"] : data[\"birthstring\"]", "birth,cellphone): user = User(loginid, name, password) user.gender = gender user.address = address user.role", "DBP.models import Base,session from sqlalchemy import Column, Integer, Unicode, Enum, Date, String from", "== user.id).all() for p in ps: for t in p.tasks: session.delete(t) session.delete(p) for", "x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id, \"loginid\" : self.loginid,", "address user.role = role user.birth = datetime.strptime(birth, \"%a %b %d %Y\").date() user.cellphone =", "submitinfo return info def setStatus(self,status): self.status = status session.commit() @staticmethod def randomEvaluator(): maxnum", "utf-8 -*- from DBP.models import Base,session from sqlalchemy import Column, Integer, Unicode, Enum,", "= Column('userid', Integer, ForeignKey('User.id'), nullable = False) status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False", "Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default = u\"남자\") address = Column(Unicode(255)) role =", "== u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return session.query(User).get(id) @staticmethod def", "self.name, \"gender\" : self.gender, \"address\" : self.address, \"role\" : self.role, \"score\" : self.score,", ": return None @staticmethod def deleteUser(user): for en in user.enrolls: en.task.setTables() ps =", "= False, server_default = u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"),", "= (PrimaryKeyConstraint('taskprefix','userid',name='enroll_pk'),) taskprefix = Column('taskprefix', Unicode(100), ForeignKey('Task.prefix'), nullable = False) userid = Column('userid',", "대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인 거절\", } class Enroll(Base): __tablename__", "0, taskdata = 0) for en in self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid ==", "\"role\" : self.role, \"score\" : self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\"", "if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return data def enrollStatus(self): enrolls = list()", "generate_password_hash, check_password_hash enrollcode = { \"Waiting\" : u\"승인 대기중\", \"Approved\" : u\"승인 완료\",", "sqlalchemy.orm import relationship from sqlalchemy.sql import func from datetime import datetime import random", "= list() for en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status ==", "user = User(loginid, name, password) user.gender = gender user.address = address user.role =", "= name self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def dict(self): tslist", ": u\"승인 대기중\", \"Approved\" : u\"승인 완료\", \"Refused\" : u\"승인 거절\", } class", "self.password = generate_password_hash(password) self.name = name self.gender = gender self.address = address self.birth", "from sqlalchemy.sql import func from datetime import datetime import random from werkzeug.security import", "ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps: for t in p.tasks:", "status session.commit() @staticmethod def randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum ==", "= Column(String(100), nullable = False) name = Column(Unicode(100), nullable = False) gender =", "status = Column('status',Enum(u\"Waiting\",u\"Approved\",u\"Refused\"), nullable = False , server_default = \"Waiting\") user = relationship(\"User\",", "Enum, Date, String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label", "user.gender = gender user.address = address user.role = role user.birth = datetime.strptime(birth, \"%a", "= u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return enrolls def editInfo(self,", "and user.checkPassword(password) : return user else : return None @staticmethod def deleteUser(user): for", "list() for en in self.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status == u\"Evaluated\").all()", "\"%a %b %d %Y\").date() self.cellphone = cellphone session.commit() def setScore(self): sums = list()", "u\"남자\") address = Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default", "self.enrolls: en.task.setTables() submitinfo[\"parsed\"] += session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).count() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == self.id).filter(en.task.parsed.status ==", "\"gender\" : self.gender, \"address\" : self.address, \"role\" : self.role, \"score\" : self.score, \"birthstring\"", "password) user.gender = gender user.address = address user.role = role user.birth = datetime.strptime(birth,", "user.enrolls: en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps: for t", "= Column(Integer, primary_key=True, autoincrement = True, nullable = False) loginid = Column(Unicode(100), unique", "loginid self.name = name self.password = generate_password_hash(password) def checkPassword(self,password): return check_password_hash(self.password, password) def", "= x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"] = x.task.getTaskNumBySubmitter(self) tslist.append(ts) data = {\"id\" : self.id, \"loginid\" :", "sqlalchemy.sql import func from datetime import datetime import random from werkzeug.security import generate_password_hash,", "Column(Unicode(255)) role = Column(Enum(u\"관리자\", u\"제출자\", u\"평가자\"), nullable = False, server_default = u\"제출자\") score", "session.query(User).filter(User.loginid == loginid).first() if user and user.checkPassword(password) : return user else : return", "password = Column(String(100), nullable = False) name = Column(Unicode(100), nullable = False) gender", "en.task.setTables() ps = session.query(en.task.parsed).filter(en.task.parsed.submitterid == user.id).all() for p in ps: for t in", "Integer, Unicode, Enum, Date, String from sqlalchemy import Table, ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression", "randomEvaluator(): maxnum = session.query(User).filter(User.role == u\"평가자\").count() if maxnum == 0: return session.query(User).filter(User.role ==", "def enrollStatus(self): enrolls = list() for enroll in self.enrolls: task = enroll.task.dict() if", "func from datetime import datetime import random from werkzeug.security import generate_password_hash, check_password_hash enrollcode", "False) birth = Column(Date) cellphone = Column(Unicode(15)) def __init__(self,loginid,name,password): self.loginid = loginid self.name", ": self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"] : data[\"birthstring\"] = data[\"birthstring\"].isoformat() return", "== \"Stop\": task[\"status\"] = u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task) return", "self.score, \"birthstring\" : self.birth, \"cellphone\" : self.cellphone, \"tasks\" : tslist } if data[\"birthstring\"]", "getSubmitInfo(self): info = self.dict() submitinfo = dict(parsed = 0, taskdata = 0) for", "ForeignKey, PrimaryKeyConstraint from sqlalchemy.sql.expression import label from sqlalchemy.orm import relationship from sqlalchemy.sql import", "gender = Column(Enum(u\"남자\", u\"여자\"), nullable = False, server_default = u\"남자\") address = Column(Unicode(255))", "= cellphone session.commit() def setScore(self): sums = list() for en in self.enrolls: en.task.setTables()", "self.cellphone = cellphone session.commit() def setScore(self): sums = list() for en in self.enrolls:", "[] for x in self.enrolls: x.task.setTables() ts = x.task.dict() ts[\"parsednum\"] = x.task.getParsedNumBySubmitter(self) ts[\"tasknum\"]", "nullable = False) password = Column(String(100), nullable = False) name = Column(Unicode(100), nullable", "task[\"status\"] == \"Stop\": task[\"status\"] = u\"수집 종료\" else : task[\"status\"] = enrollcode[enroll.status] enrolls.append(task)", "0: return session.query(User).filter(User.role == u\"관리자\").first() return session.query(User).filter(User.role == u\"평가자\")[random.randrange(0,maxnum)] @staticmethod def getUser(id): return", "%b %d %Y\").date() self.cellphone = cellphone session.commit() def setScore(self): sums = list() for", "session.query(User).get(id) @staticmethod def getUsers(): return session.query(User).order_by(User.id).all() @staticmethod def newUser(loginid, password, name, gender, address", "Column(Integer, server_default = \"0\", nullable = False) birth = Column(Date) cellphone = Column(Unicode(15))" ]
[ "y - h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1", "get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the predicted bounding boxes :return:", "ground truth bounding boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\"", "h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1", "image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2, y - h / 2, w,", "ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count = 0 def", "self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2, y - h /", "F class ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count =", "= [] self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list", "the predicted bounding boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp", "1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images =", "return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp = self._img_count for target in targets:", "predictions): img_count_temp = self._img_count for target in targets: for label, [x, y, w,", "[x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w", "-> List[BoundingBox]: \"\"\" Returns a list containing the ground truth bounding boxes :return:", "= predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1) for", "in targets: for label, [x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count),", "for scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score, label, [x, y,", "[x, y, w, h] in zip(scores, labels, pred_boxes): label = label.item() score =", "= 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the ground", ")) self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1)", "src.bounding_box import BoundingBox from src.utils.enumerators import BBType, BBFormat import torch.nn.functional as F class", "for label, [x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x", "y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w /", "/ 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images =", "[] self._predicted_bboxes = [] self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns", "scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score, label, [x, y, w,", "get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the ground truth bounding boxes", "zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2, y - h", "\"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp = self._img_count for target in", "pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score, label, [x, y, w, h] in", "/ 2, y - h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score )", "self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]:", "\"\"\" Returns a list containing the ground truth bounding boxes :return: \"\"\" return", "w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1 @abstractmethod def get_metrics(self)", "class ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count = 0", "a list containing the ground truth bounding boxes :return: \"\"\" return self._gt_bboxes def", "w / 2, y - h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, ))", "labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score, label, [x, y, w, h]", "w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2,", "from src.utils.enumerators import BBType, BBFormat import torch.nn.functional as F class ModelEvaluator: def __init__(self):", "= [] self._predicted_bboxes = [] self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\"", "Returns a list containing the predicted bounding boxes :return: \"\"\" return self._predicted_bboxes def", "coordinates=(x - w / 2, y - h / 2, w, h), bb_type=BBType.GROUND_TRUTH,", "truth bounding boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns", "score, label, [x, y, w, h] in zip(scores, labels, pred_boxes): label = label.item()", "Returns a list containing the ground truth bounding boxes :return: \"\"\" return self._gt_bboxes", "bounding boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a", "2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1 @abstractmethod def", "src.utils.enumerators import BBType, BBFormat import torch.nn.functional as F class ModelEvaluator: def __init__(self): self._gt_bboxes", "boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp = self._img_count for", ":return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp = self._img_count for target", "BBFormat import torch.nn.functional as F class ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes", "0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2, y - h", "+= 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images", "predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1) for scores, labels,", "= score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w", "predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1) for scores,", "label.item() score = score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x", "Dict from src.bounding_box import BoundingBox from src.utils.enumerators import BBType, BBFormat import torch.nn.functional as", "label, [x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x -", "self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the predicted bounding", "-> List[BoundingBox]: \"\"\" Returns a list containing the predicted bounding boxes :return: \"\"\"", "targets, predictions): img_count_temp = self._img_count for target in targets: for label, [x, y,", "from src.bounding_box import BoundingBox from src.utils.enumerators import BBType, BBFormat import torch.nn.functional as F", "- h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits,", "coordinates=(x - w / 2, y - h / 2, w, h), bb_type=BBType.DETECTED,", "List, Dict from src.bounding_box import BoundingBox from src.utils.enumerators import BBType, BBFormat import torch.nn.functional", "w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes']", "BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2, y - h / 2,", "label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2, y", "as F class ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count", "import abstractmethod from typing import List, Dict from src.bounding_box import BoundingBox from src.utils.enumerators", "-1) scores_images, labels_images = prob[..., :-1].max(-1) for scores, labels, pred_boxes in zip(scores_images, labels_images,", "h] in zip(scores, labels, pred_boxes): label = label.item() score = score.item() if label", ">= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2, y -", "h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images", "def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the ground truth bounding", "- w / 2, y - h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH,", "labels_images = prob[..., :-1].max(-1) for scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for", "self._predicted_bboxes = [] self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a", "\"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the", ":-1].max(-1) for scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score, label, [x,", "h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2, y", "return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the predicted", "bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1 @abstractmethod def get_metrics(self) -> Dict:", "pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1)", "F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1) for scores, labels, pred_boxes in zip(scores_images,", "list containing the predicted bounding boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets,", "BBType, BBFormat import torch.nn.functional as F class ModelEvaluator: def __init__(self): self._gt_bboxes = []", "abstractmethod from typing import List, Dict from src.bounding_box import BoundingBox from src.utils.enumerators import", "predicted bounding boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp =", "scores_images, labels_images = prob[..., :-1].max(-1) for scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images):", "from abc import abstractmethod from typing import List, Dict from src.bounding_box import BoundingBox", "torch.nn.functional as F class ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes = []", "w, h] in zip(scores, labels, pred_boxes): label = label.item() score = score.item() if", "def __init__(self): self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count = 0 def get_gt_bboxes(self)", "self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2, y - h / 2,", "y - h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp", "target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2, y - h /", "h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1 @abstractmethod def get_metrics(self) ->", "labels_images, pred_boxes_images): for score, label, [x, y, w, h] in zip(scores, labels, pred_boxes):", "format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1 @abstractmethod def get_metrics(self) -> Dict: pass", "/ 2, y - h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count", "in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label), coordinates=(x - w / 2, y -", "import BBType, BBFormat import torch.nn.functional as F class ModelEvaluator: def __init__(self): self._gt_bboxes =", "bounding boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp = self._img_count", "\"\"\" Returns a list containing the predicted bounding boxes :return: \"\"\" return self._predicted_bboxes", "target in targets: for label, [x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox(", "= self._img_count for target in targets: for label, [x, y, w, h] in", "y, w, h] in zip(scores, labels, pred_boxes): label = label.item() score = score.item()", "List[BoundingBox]: \"\"\" Returns a list containing the predicted bounding boxes :return: \"\"\" return", "label = label.item() score = score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp),", "pred_boxes_images): for score, label, [x, y, w, h] in zip(scores, labels, pred_boxes): label", "for score, label, [x, y, w, h] in zip(scores, labels, pred_boxes): label =", "import torch.nn.functional as F class ModelEvaluator: def __init__(self): self._gt_bboxes = [] self._predicted_bboxes =", "format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits,", "- h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp +=", "- w / 2, y - h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH,", "score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w /", "def add_predictions(self, targets, predictions): img_count_temp = self._img_count for target in targets: for label,", "= label.item() score = score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label),", "image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2, y - h / 2, w,", "score = score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x -", "containing the predicted bounding boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self, targets, predictions):", "class_id=str(label), coordinates=(x - w / 2, y - h / 2, w, h),", "zip(scores, labels, pred_boxes): label = label.item() score = score.item() if label >= 0:", "bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob =", "if label >= 0: self._predicted_bboxes.append( BoundingBox( image_name=str(img_count_temp), class_id=str(label), coordinates=(x - w / 2,", "in zip(scores_images, labels_images, pred_boxes_images): for score, label, [x, y, w, h] in zip(scores,", "img_count_temp = self._img_count for target in targets: for label, [x, y, w, h]", "boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list", "h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob", "0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the ground truth", "a list containing the predicted bounding boxes :return: \"\"\" return self._predicted_bboxes def add_predictions(self,", "List[BoundingBox]: \"\"\" Returns a list containing the ground truth bounding boxes :return: \"\"\"", "self._img_count for target in targets: for label, [x, y, w, h] in zip(target['labels'].tolist(),", "self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images,", ":return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing", "= prob[..., :-1].max(-1) for scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score,", "self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the", "in zip(scores, labels, pred_boxes): label = label.item() score = score.item() if label >=", "BoundingBox from src.utils.enumerators import BBType, BBFormat import torch.nn.functional as F class ModelEvaluator: def", "[] self._img_count = 0 def get_gt_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing", "self._predicted_bboxes def add_predictions(self, targets, predictions): img_count_temp = self._img_count for target in targets: for", "pred_boxes): label = label.item() score = score.item() if label >= 0: self._predicted_bboxes.append( BoundingBox(", "label, [x, y, w, h] in zip(scores, labels, pred_boxes): label = label.item() score", "targets: for label, [x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()): self._gt_bboxes.append(BoundingBox( image_name=str(self._img_count), class_id=str(label),", "2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count += 1 pred_logits, pred_boxes_images = predictions['pred_logits'],", "add_predictions(self, targets, predictions): img_count_temp = self._img_count for target in targets: for label, [x,", "typing import List, Dict from src.bounding_box import BoundingBox from src.utils.enumerators import BBType, BBFormat", "2, y - h / 2, w, h), bb_type=BBType.GROUND_TRUTH, format=BBFormat.XYWH, )) self._img_count +=", "__init__(self): self._gt_bboxes = [] self._predicted_bboxes = [] self._img_count = 0 def get_gt_bboxes(self) ->", "prob = F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1) for scores, labels, pred_boxes", "w / 2, y - h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score", "import List, Dict from src.bounding_box import BoundingBox from src.utils.enumerators import BBType, BBFormat import", "pred_logits, pred_boxes_images = predictions['pred_logits'], predictions['pred_boxes'] prob = F.softmax(pred_logits, -1) scores_images, labels_images = prob[...,", "= F.softmax(pred_logits, -1) scores_images, labels_images = prob[..., :-1].max(-1) for scores, labels, pred_boxes in", "the ground truth bounding boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) -> List[BoundingBox]:", "list containing the ground truth bounding boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self)", "2, y - h / 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) )", "prob[..., :-1].max(-1) for scores, labels, pred_boxes in zip(scores_images, labels_images, pred_boxes_images): for score, label,", "def get_predicted_bboxes(self) -> List[BoundingBox]: \"\"\" Returns a list containing the predicted bounding boxes", "zip(scores_images, labels_images, pred_boxes_images): for score, label, [x, y, w, h] in zip(scores, labels,", "labels, pred_boxes): label = label.item() score = score.item() if label >= 0: self._predicted_bboxes.append(", "/ 2, w, h), bb_type=BBType.DETECTED, format=BBFormat.XYWH, confidence=score ) ) img_count_temp += 1 @abstractmethod", "containing the ground truth bounding boxes :return: \"\"\" return self._gt_bboxes def get_predicted_bboxes(self) ->", "abc import abstractmethod from typing import List, Dict from src.bounding_box import BoundingBox from", "import BoundingBox from src.utils.enumerators import BBType, BBFormat import torch.nn.functional as F class ModelEvaluator:", "from typing import List, Dict from src.bounding_box import BoundingBox from src.utils.enumerators import BBType,", "for target in targets: for label, [x, y, w, h] in zip(target['labels'].tolist(), target['boxes'].tolist()):" ]
[ "get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections. Assume credentials are in", "bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read' key =", "such # an download_file and upload_file, nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\"", "in common utility functions, such # an download_file and upload_file, nothing \"dangerous\" like", "boto.connect_s3() # Have a default bucket, so individual function calls don't # need", "import boto from ..common import get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish", "# \"empty_bucket\" or \"delete_bucket.\" if bucket is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID')", "functions, such # an download_file and upload_file, nothing \"dangerous\" like # \"empty_bucket\" or", "only be used in common utility functions, such # an download_file and upload_file,", "from ..common import get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections. Assume", "def upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers)", "bucket=None): \"\"\" Establish connections. Assume credentials are in environment or in a config", "file. \"\"\" self.s3_conn = boto.connect_s3() # Have a default bucket, so individual function", "key, headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def", "used in common utility functions, such # an download_file and upload_file, nothing \"dangerous\"", "is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers):", "__init__(self, bucket=None): \"\"\" Establish connections. Assume credentials are in environment or in a", "download_file and upload_file, nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if bucket is", "or in a config file. \"\"\" self.s3_conn = boto.connect_s3() # Have a default", "like # \"empty_bucket\" or \"delete_bucket.\" if bucket is not None: self.bucket = bucket", "function calls don't # need to query global settings and pass the bucket", "or \"delete_bucket.\" if bucket is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def", "S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections. Assume credentials are in environment or", "connections. Assume credentials are in environment or in a config file. \"\"\" self.s3_conn", "\"delete_bucket.\" if bucket is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self,", "# an download_file and upload_file, nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if", "pass the bucket each time. # self.bucket will only be used in common", "and pass the bucket each time. # self.bucket will only be used in", "= self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def close(self): \"\"\" Close connection. \"\"\" self.s3_conn.close()", "config file. \"\"\" self.s3_conn = boto.connect_s3() # Have a default bucket, so individual", "be used in common utility functions, such # an download_file and upload_file, nothing", "will only be used in common utility functions, such # an download_file and", "environment or in a config file. \"\"\" self.s3_conn = boto.connect_s3() # Have a", "get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content,", "Establish connections. Assume credentials are in environment or in a config file. \"\"\"", "content, key, headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key", "'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def close(self): \"\"\" Close connection.", "query global settings and pass the bucket each time. # self.bucket will only", "each time. # self.bucket will only be used in common utility functions, such", "None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl'] =", "= boto.connect_s3() # Have a default bucket, so individual function calls don't #", "\"empty_bucket\" or \"delete_bucket.\" if bucket is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY')", "# self.bucket will only be used in common utility functions, such # an", "key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def close(self): \"\"\" Close connection. \"\"\"", "need to query global settings and pass the bucket each time. # self.bucket", "nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if bucket is not None: self.bucket", "if bucket is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content,", "\"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if bucket is not None: self.bucket =", "a default bucket, so individual function calls don't # need to query global", "global settings and pass the bucket each time. # self.bucket will only be", "..common import get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections. Assume credentials", "settings and pass the bucket each time. # self.bucket will only be used", "individual function calls don't # need to query global settings and pass the", "def __init__(self, bucket=None): \"\"\" Establish connections. Assume credentials are in environment or in", "# Have a default bucket, so individual function calls don't # need to", "are in environment or in a config file. \"\"\" self.s3_conn = boto.connect_s3() #", "an download_file and upload_file, nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if bucket", "Have a default bucket, so individual function calls don't # need to query", "utility functions, such # an download_file and upload_file, nothing \"dangerous\" like # \"empty_bucket\"", "# need to query global settings and pass the bucket each time. #", "in environment or in a config file. \"\"\" self.s3_conn = boto.connect_s3() # Have", "and upload_file, nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if bucket is not", "self.bucket will only be used in common utility functions, such # an download_file", "boto from ..common import get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections.", "calls don't # need to query global settings and pass the bucket each", "= 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def close(self): \"\"\" Close", "= bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read' key", "\"\"\" Establish connections. Assume credentials are in environment or in a config file.", "in a config file. \"\"\" self.s3_conn = boto.connect_s3() # Have a default bucket,", "don't # need to query global settings and pass the bucket each time.", "\"\"\" self.s3_conn = boto.connect_s3() # Have a default bucket, so individual function calls", "<filename>publishstatic/management/commands/storage/s3.py import boto from ..common import get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\"", "upload_file, nothing \"dangerous\" like # \"empty_bucket\" or \"delete_bucket.\" if bucket is not None:", "headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def close(self):", "get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key)", "self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read'", "so individual function calls don't # need to query global settings and pass", "bucket is not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key,", "import get_required_env_variable class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections. Assume credentials are", "default bucket, so individual function calls don't # need to query global settings", "not None: self.bucket = bucket get_required_env_variable('AWS_ACCESS_KEY_ID') get_required_env_variable('AWS_SECRET_ACCESS_KEY') def upload_contents(self, content, key, headers): headers['x-amz-acl']", "self.s3_conn = boto.connect_s3() # Have a default bucket, so individual function calls don't", "class S3Storage(object): def __init__(self, bucket=None): \"\"\" Establish connections. Assume credentials are in environment", "a config file. \"\"\" self.s3_conn = boto.connect_s3() # Have a default bucket, so", "the bucket each time. # self.bucket will only be used in common utility", "credentials are in environment or in a config file. \"\"\" self.s3_conn = boto.connect_s3()", "headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return key def close(self): \"\"\"", "bucket, so individual function calls don't # need to query global settings and", "to query global settings and pass the bucket each time. # self.bucket will", "bucket each time. # self.bucket will only be used in common utility functions,", "common utility functions, such # an download_file and upload_file, nothing \"dangerous\" like #", "Assume credentials are in environment or in a config file. \"\"\" self.s3_conn =", "upload_contents(self, content, key, headers): headers['x-amz-acl'] = 'public-read' key = self.bucket.new_key(key) key.set_contents_from_file(content, headers) return", "time. # self.bucket will only be used in common utility functions, such #" ]
[ "= filename or w.filename lineno = lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else:", "defaultdict import warnings # Filled at the end __all__ = [] class NumbaWarning(Warning):", "% (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was encountered (e.g.", "A forbidden Python construct was encountered (e.g. use of locals()). \"\"\" class TypingError(NumbaError):", "self.loc return \"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class", "(name, value) in globals().items() if not name.startswith('_') and isinstance(value, type) and issubclass(value, (Exception,", "import warnings # Filled at the end __all__ = [] class NumbaWarning(Warning): \"\"\"", "error occurred during Numba IR generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def", "lineno, w.category].add(msg) else: # Simply emit other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno)", "lowering. \"\"\" def __init__(self, msg, loc): self.msg = msg self.loc = loc super(LoweringError,", "\"\"\" from __future__ import print_function, division, absolute_import import contextlib from collections import defaultdict", "= name self.loc = loc def __str__(self): loc = \"?\" if self.loc is", "in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception):", "locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type inference failure. \"\"\" def __init__(self, msg,", "else self.loc return \"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass", "this category for deduplication filename = filename or w.filename lineno = lineno or", "for (filename, lineno, category), messages in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category,", "category), messages in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear()", "class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name = name self.loc = loc def", "defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error occurred", "class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name = name self.loc", "\"\"\" A forbidden Python construct was encountered (e.g. use of locals()). \"\"\" class", "An error occurred during lowering. \"\"\" def __init__(self, msg, loc): self.msg = msg", "class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg = 'Unknown attribute \"{attr}\" of", "filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error occurred during", "\"\"\" An error occurred during Numba IR generation. \"\"\" class RedefinedError(IRError): pass class", "% (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value,", "in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\" __all__", "CompilerError(NumbaError): \"\"\" Some high-level error in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure", "wlist: msg = str(w.message) if issubclass(w.category, self._category): # Store warnings of this category", "use of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type inference failure. \"\"\" def", "sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An", "warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for w in wlist: msg = str(w.message)", "fix their filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield", "\"fixing\" warnings of a given category caught during certain phases. The warnings can", "warnings # Filled at the end __all__ = [] class NumbaWarning(Warning): \"\"\" Base", "warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit all stored warnings.", "constant inference. \"\"\" __all__ += [name for (name, value) in globals().items() if not", "ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode of the user's function. \"\"\" class", "not be as fast as expected. \"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\"", "pass class IRError(NumbaError): \"\"\" An error occurred during Numba IR generation. \"\"\" class", "during certain phases. The warnings can have their filename and lineno fixed, and", "error occurred during lowering. \"\"\" def __init__(self, msg, loc): self.msg = msg self.loc", "if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class", "An object \"fixing\" warnings of a given category caught during certain phases. The", "def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and optionally fix their filename and", "class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\" __all__ += [name for (name,", "might not be as fast as expected. \"\"\" class WarningsFixer(object): \"\"\" An object", "user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error in the compiler. \"\"\"", "loc = \"?\" if self.loc is None else self.loc return \"{name!r} is not", "if self.loc is None else self.loc return \"{name!r} is not defined in {loc}\".format(name=self.name,", "all stored warnings. \"\"\" for (filename, lineno, category), messages in sorted(self._warnings.items()): for msg", "msg = 'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class", "from collections import defaultdict import warnings # Filled at the end __all__ =", "DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error occurred during lowering. \"\"\" def __init__(self,", "\"\"\" An object \"fixing\" warnings of a given category caught during certain phases.", "construct was encountered (e.g. use of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type", "w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit all stored warnings. \"\"\" for (filename,", "of this category for deduplication filename = filename or w.filename lineno = lineno", "self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg = 'Unknown", "\"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error occurred during lowering. \"\"\"", "given category caught during certain phases. The warnings can have their filename and", "failure. \"\"\" def __init__(self, msg, loc=None): self.msg = msg self.loc = loc if", "catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and optionally fix their filename and lineno.", "(filename, lineno, category), messages in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category, filename,", "VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error occurred during macro expansion. \"\"\" class", "loc=None): self.msg = msg self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg,", "operation might not be as fast as expected. \"\"\" class WarningsFixer(object): \"\"\" An", "filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for w", "flush(self): \"\"\" Emit all stored warnings. \"\"\" for (filename, lineno, category), messages in", "warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit all stored warnings. \"\"\" for", "LoweringError(NumbaError): \"\"\" An error occurred during lowering. \"\"\" def __init__(self, msg, loc): self.msg", "was encountered (e.g. use of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type inference", "An error occurred during macro expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\"", "__init__(self, value, attr, loc=None): msg = 'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr)", "def __init__(self, name, loc=None): self.name = name self.loc = loc def __str__(self): loc", "\"\"\" def __init__(self, msg, loc): self.msg = msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\"", "category for all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for", "= [] class NumbaWarning(Warning): \"\"\" Base category for all Numba compiler warnings. \"\"\"", "(msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr,", "def __init__(self, category): self._category = category # {(filename, lineno, category) -> messages} self._warnings", "warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error", "value, attr, loc=None): msg = 'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError,", "in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error occurred during", "during Numba IR generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name,", "the end __all__ = [] class NumbaWarning(Warning): \"\"\" Base category for all Numba", "for deduplication filename = filename or w.filename lineno = lineno or w.lineno self._warnings[filename,", "are deduplicated as well. \"\"\" def __init__(self, category): self._category = category # {(filename,", "of the user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error in the", "__all__ += [name for (name, value) in globals().items() if not name.startswith('_') and isinstance(value,", "= msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\"", "filename = filename or w.filename lineno = lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg)", "An error occurred during Numba IR generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError):", "\"\"\" def __init__(self, category): self._category = category # {(filename, lineno, category) -> messages}", "Numba IR generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name, loc=None):", "extract the bytecode of the user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level", "IR generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name", "of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract", "MacroError(NumbaError): \"\"\" An error occurred during macro expansion. \"\"\" class DeprecationError(NumbaError): pass class", "when an operation might not be as fast as expected. \"\"\" class WarningsFixer(object):", "Store warnings and optionally fix their filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as", "import contextlib from collections import defaultdict import warnings # Filled at the end", "lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for w in wlist:", "class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error occurred during Numba IR generation.", "loc def __str__(self): loc = \"?\" if self.loc is None else self.loc return", "{loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error occurred during macro", "well. \"\"\" def __init__(self, category): self._category = category # {(filename, lineno, category) ->", "warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an operation might not", "w.filename, w.lineno) def flush(self): \"\"\" Emit all stored warnings. \"\"\" for (filename, lineno,", "for w in wlist: msg = str(w.message) if issubclass(w.category, self._category): # Store warnings", "defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and optionally fix their", "bytecode of the user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error in", "= defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and optionally fix", "warnings. \"\"\" for (filename, lineno, category), messages in sorted(self._warnings.items()): for msg in sorted(messages):", "sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass", "= loc def __str__(self): loc = \"?\" if self.loc is None else self.loc", "class IRError(NumbaError): \"\"\" An error occurred during Numba IR generation. \"\"\" class RedefinedError(IRError):", "type inference failure. \"\"\" def __init__(self, msg, loc=None): self.msg = msg self.loc =", "filename or w.filename lineno = lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: #", "w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit other warnings again warnings.warn_explicit(msg, w.category,", "errors and warnings. \"\"\" from __future__ import print_function, division, absolute_import import contextlib from", "# Filled at the end __all__ = [] class NumbaWarning(Warning): \"\"\" Base category", "self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error occurred during Numba IR", "expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error occurred during lowering.", "again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit all stored warnings. \"\"\"", "optionally fix their filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category)", "\"?\" if self.loc is None else self.loc return \"{name!r} is not defined in", "category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error occurred", "fast as expected. \"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\" warnings of a", "they are deduplicated as well. \"\"\" def __init__(self, category): self._category = category #", "= msg self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else:", "-> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings", "Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an operation", "inference failure. \"\"\" def __init__(self, msg, loc=None): self.msg = msg self.loc = loc", "class WarningsFixer(object): \"\"\" An object \"fixing\" warnings of a given category caught during", "NumbaWarning(Warning): \"\"\" Base category for all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\"", "at the end __all__ = [] class NumbaWarning(Warning): \"\"\" Base category for all", "deduplication filename = filename or w.filename lineno = lineno or w.lineno self._warnings[filename, lineno,", "msg, loc=None): self.msg = msg self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" %", "as well. \"\"\" def __init__(self, category): self._category = category # {(filename, lineno, category)", "\"\"\" A type inference failure. \"\"\" def __init__(self, msg, loc=None): self.msg = msg", "object \"fixing\" warnings of a given category caught during certain phases. The warnings", "to extract the bytecode of the user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some", "ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was encountered (e.g. use of locals()). \"\"\"", "their filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for", "[] class NumbaWarning(Warning): \"\"\" Base category for all Numba compiler warnings. \"\"\" class", "class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an operation might not be as", "or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit other warnings again warnings.warn_explicit(msg,", "warnings can have their filename and lineno fixed, and they are deduplicated as", "% (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg = 'Unknown attribute", "and lineno fixed, and they are deduplicated as well. \"\"\" def __init__(self, category):", "of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type inference failure. \"\"\" def __init__(self,", "emit other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit all", "as fast as expected. \"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\" warnings of", "msg, loc): self.msg = msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat()))", "in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\"", "__init__(self, name, loc=None): self.name = name self.loc = loc def __str__(self): loc =", "self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was encountered", "for msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class", "WarningsFixer(object): \"\"\" An object \"fixing\" warnings of a given category caught during certain", "Python construct was encountered (e.g. use of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A", "The warnings can have their filename and lineno fixed, and they are deduplicated", "if issubclass(w.category, self._category): # Store warnings of this category for deduplication filename =", "self.name = name self.loc = loc def __str__(self): loc = \"?\" if self.loc", "loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,))", "RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name = name self.loc =", "high-level error in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference.", "attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode of", "compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\" __all__ += [name", "Base category for all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category", "msg self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError,", "import print_function, division, absolute_import import contextlib from collections import defaultdict import warnings #", "issubclass(w.category, self._category): # Store warnings of this category for deduplication filename = filename", "\"\"\" Failure during constant inference. \"\"\" __all__ += [name for (name, value) in", "__all__ = [] class NumbaWarning(Warning): \"\"\" Base category for all Numba compiler warnings.", "\"\"\" for (filename, lineno, category), messages in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg,", "a given category caught during certain phases. The warnings can have their filename", "return \"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError):", "= str(w.message) if issubclass(w.category, self._category): # Store warnings of this category for deduplication", "__future__ import print_function, division, absolute_import import contextlib from collections import defaultdict import warnings", "= loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" %", "division, absolute_import import contextlib from collections import defaultdict import warnings # Filled at", "__init__(self, msg, loc): self.msg = msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg,", "category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store", "= 'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError):", "caught during certain phases. The warnings can have their filename and lineno fixed,", "of a given category caught during certain phases. The warnings can have their", "\"\"\" Warning category for when an operation might not be as fast as", "name, loc=None): self.name = name self.loc = loc def __str__(self): loc = \"?\"", "filename=None, lineno=None): \"\"\" Store warnings and optionally fix their filename and lineno. \"\"\"", "def flush(self): \"\"\" Emit all stored warnings. \"\"\" for (filename, lineno, category), messages", "\"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an operation might not be", "{(filename, lineno, category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None):", "the bytecode of the user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error", "lineno, category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\"", "= \"?\" if self.loc is None else self.loc return \"{name!r} is not defined", "class MacroError(NumbaError): \"\"\" An error occurred during macro expansion. \"\"\" class DeprecationError(NumbaError): pass", "all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an", "UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg = 'Unknown attribute \"{attr}\" of type", "Emit all stored warnings. \"\"\" for (filename, lineno, category), messages in sorted(self._warnings.items()): for", "Failure during constant inference. \"\"\" __all__ += [name for (name, value) in globals().items()", "in wlist: msg = str(w.message) if issubclass(w.category, self._category): # Store warnings of this", "class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error occurred during macro expansion. \"\"\"", "self._category = category # {(filename, lineno, category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager", "from __future__ import print_function, division, absolute_import import contextlib from collections import defaultdict import", "class LoweringError(NumbaError): \"\"\" An error occurred during lowering. \"\"\" def __init__(self, msg, loc):", "self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self,", "their filename and lineno fixed, and they are deduplicated as well. \"\"\" def", "IRError(NumbaError): \"\"\" An error occurred during Numba IR generation. \"\"\" class RedefinedError(IRError): pass", "pass class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name = name self.loc = loc", "\"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for w in wlist: msg", "macro expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error occurred during", "loc): self.msg = msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class", "w.lineno) def flush(self): \"\"\" Emit all stored warnings. \"\"\" for (filename, lineno, category),", "with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for w in wlist: msg =", "can have their filename and lineno fixed, and they are deduplicated as well.", "pass class MacroError(NumbaError): \"\"\" An error occurred during macro expansion. \"\"\" class DeprecationError(NumbaError):", "name self.loc = loc def __str__(self): loc = \"?\" if self.loc is None", "A type inference failure. \"\"\" def __init__(self, msg, loc=None): self.msg = msg self.loc", "lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error occurred during Numba", "during lowering. \"\"\" def __init__(self, msg, loc): self.msg = msg self.loc = loc", "\"\"\" Base category for all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning", "loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was encountered (e.g. use of", "super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was", "compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an operation might", "category for when an operation might not be as fast as expected. \"\"\"", "class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error occurred during lowering. \"\"\" def", "class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode of the user's function. \"\"\"", "\"\"\" def __init__(self, msg, loc=None): self.msg = msg self.loc = loc if loc:", "warnings. \"\"\" from __future__ import print_function, division, absolute_import import contextlib from collections import", "msg = str(w.message) if issubclass(w.category, self._category): # Store warnings of this category for", "class NumbaWarning(Warning): \"\"\" Base category for all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning):", "category): self._category = category # {(filename, lineno, category) -> messages} self._warnings = defaultdict(set)", "str(w.message) if issubclass(w.category, self._category): # Store warnings of this category for deduplication filename", "wlist: warnings.simplefilter('always', self._category) yield for w in wlist: msg = str(w.message) if issubclass(w.category,", "= loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python", "error occurred during macro expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An", "Numba-specific errors and warnings. \"\"\" from __future__ import print_function, division, absolute_import import contextlib", "and they are deduplicated as well. \"\"\" def __init__(self, category): self._category = category", "filename and lineno fixed, and they are deduplicated as well. \"\"\" def __init__(self,", "value) in globals().items() if not name.startswith('_') and isinstance(value, type) and issubclass(value, (Exception, Warning))]", "# {(filename, lineno, category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None,", "self.msg = msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError):", "\"\"\" Some high-level error in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during", "the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\" __all__ +=", "occurred during lowering. \"\"\" def __init__(self, msg, loc): self.msg = msg self.loc =", "for (name, value) in globals().items() if not name.startswith('_') and isinstance(value, type) and issubclass(value,", "@contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and optionally fix their filename", "type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the", "\"\"\" Failure to extract the bytecode of the user's function. \"\"\" class CompilerError(NumbaError):", "msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class NumbaError(Exception): pass class IRError(NumbaError):", "lineno = lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit other", "loc=None): self.name = name self.loc = loc def __str__(self): loc = \"?\" if", "have their filename and lineno fixed, and they are deduplicated as well. \"\"\"", "def __str__(self): loc = \"?\" if self.loc is None else self.loc return \"{name!r}", "generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name =", "super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode of the", "self.loc is None else self.loc return \"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc)", "is not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An", "attr, loc=None): msg = 'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg,", "\"\"\" Store warnings and optionally fix their filename and lineno. \"\"\" with warnings.catch_warnings(record=True)", "\"\"\" __all__ += [name for (name, value) in globals().items() if not name.startswith('_') and", "as wlist: warnings.simplefilter('always', self._category) yield for w in wlist: msg = str(w.message) if", "loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct", "forbidden Python construct was encountered (e.g. use of locals()). \"\"\" class TypingError(NumbaError): \"\"\"", "inference. \"\"\" __all__ += [name for (name, value) in globals().items() if not name.startswith('_')", "is None else self.loc return \"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc) class", "= category # {(filename, lineno, category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def", "self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden", "loc=None): msg = 'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc)", "an operation might not be as fast as expected. \"\"\" class WarningsFixer(object): \"\"\"", "certain phases. The warnings can have their filename and lineno fixed, and they", "loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None):", "w.category].add(msg) else: # Simply emit other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def", "None else self.loc return \"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError):", "expected. \"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\" warnings of a given category", "def __init__(self, msg, loc=None): self.msg = msg self.loc = loc if loc: super(TypingError,", "deduplicated as well. \"\"\" def __init__(self, category): self._category = category # {(filename, lineno,", "(msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was encountered (e.g. use", "[name for (name, value) in globals().items() if not name.startswith('_') and isinstance(value, type) and", "self.msg = msg self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat()))", "Simply emit other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit", "(e.g. use of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type inference failure. \"\"\"", "self._category): # Store warnings of this category for deduplication filename = filename or", "def __init__(self, value, attr, loc=None): msg = 'Unknown attribute \"{attr}\" of type {type}'.format(type=value,", "and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always', self._category) yield for w in", "encountered (e.g. use of locals()). \"\"\" class TypingError(NumbaError): \"\"\" A type inference failure.", "end __all__ = [] class NumbaWarning(Warning): \"\"\" Base category for all Numba compiler", "category # {(filename, lineno, category) -> messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self,", "as expected. \"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\" warnings of a given", "category caught during certain phases. The warnings can have their filename and lineno", "during constant inference. \"\"\" __all__ += [name for (name, value) in globals().items() if", "occurred during Numba IR generation. \"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self,", "w.filename lineno = lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit", "TypingError(NumbaError): \"\"\" A type inference failure. \"\"\" def __init__(self, msg, loc=None): self.msg =", "warnings.simplefilter('always', self._category) yield for w in wlist: msg = str(w.message) if issubclass(w.category, self._category):", "the user's function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error in the compiler.", "warnings of this category for deduplication filename = filename or w.filename lineno =", "contextlib from collections import defaultdict import warnings # Filled at the end __all__", "Failure to extract the bytecode of the user's function. \"\"\" class CompilerError(NumbaError): \"\"\"", "function. \"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error in the compiler. \"\"\" class", "and optionally fix their filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist: warnings.simplefilter('always',", "self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and optionally", "\"\"\" class TypingError(NumbaError): \"\"\" A type inference failure. \"\"\" def __init__(self, msg, loc=None):", "lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit other warnings again", "\"\"\" class CompilerError(NumbaError): \"\"\" Some high-level error in the compiler. \"\"\" class ConstantInferenceError(NumbaError):", "messages in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno) self._warnings.clear() class", "attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure", "__init__(self, msg, loc=None): self.msg = msg self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\"", "def __init__(self, msg, loc): self.msg = msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" %", "self.loc = loc if loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\"", "not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error", "__init__(self, category): self._category = category # {(filename, lineno, category) -> messages} self._warnings =", "\"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to", "for all Numba compiler warnings. \"\"\" class PerformanceWarning(NumbaWarning): \"\"\" Warning category for when", "class TypingError(NumbaError): \"\"\" A type inference failure. \"\"\" def __init__(self, msg, loc=None): self.msg", "\"\"\" class RedefinedError(IRError): pass class NotDefinedError(IRError): def __init__(self, name, loc=None): self.name = name", "warnings of a given category caught during certain phases. The warnings can have", "error in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\"", "and warnings. \"\"\" from __future__ import print_function, division, absolute_import import contextlib from collections", "class ForbiddenConstruct(LoweringError): \"\"\" A forbidden Python construct was encountered (e.g. use of locals()).", "category for deduplication filename = filename or w.filename lineno = lineno or w.lineno", "w in wlist: msg = str(w.message) if issubclass(w.category, self._category): # Store warnings of", "during macro expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error occurred", "ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\" __all__ += [name for (name, value)", "+= [name for (name, value) in globals().items() if not name.startswith('_') and isinstance(value, type)", "stored warnings. \"\"\" for (filename, lineno, category), messages in sorted(self._warnings.items()): for msg in", "super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg =", "\"{name!r} is not defined in {loc}\".format(name=self.name, loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\"", "PerformanceWarning(NumbaWarning): \"\"\" Warning category for when an operation might not be as fast", "class CompilerError(NumbaError): \"\"\" Some high-level error in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\"", "yield for w in wlist: msg = str(w.message) if issubclass(w.category, self._category): # Store", "{type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode", "Warning category for when an operation might not be as fast as expected.", "other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\" Emit all stored", "occurred during macro expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError): \"\"\" An error", "\"\"\" An error occurred during lowering. \"\"\" def __init__(self, msg, loc): self.msg =", "for when an operation might not be as fast as expected. \"\"\" class", "= lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit other warnings", "phases. The warnings can have their filename and lineno fixed, and they are", "\"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\" warnings of a given category caught", "messages} self._warnings = defaultdict(set) @contextlib.contextmanager def catch_warnings(self, filename=None, lineno=None): \"\"\" Store warnings and", "Store warnings of this category for deduplication filename = filename or w.filename lineno", "NumbaError(Exception): pass class IRError(NumbaError): \"\"\" An error occurred during Numba IR generation. \"\"\"", "\"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant inference. \"\"\" __all__ += [name for", "'Unknown attribute \"{attr}\" of type {type}'.format(type=value, attr=attr) super(UntypedAttributeError, self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\"", "lineno fixed, and they are deduplicated as well. \"\"\" def __init__(self, category): self._category", "Some high-level error in the compiler. \"\"\" class ConstantInferenceError(NumbaError): \"\"\" Failure during constant", "self).__init__(msg, loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode of the user's", "absolute_import import contextlib from collections import defaultdict import warnings # Filled at the", "self._warnings[filename, lineno, w.category].add(msg) else: # Simply emit other warnings again warnings.warn_explicit(msg, w.category, w.filename,", "\"\"\" Numba-specific errors and warnings. \"\"\" from __future__ import print_function, division, absolute_import import", "msg self.loc = loc super(LoweringError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) class ForbiddenConstruct(LoweringError): \"\"\" A", "else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg", "loc=self.loc) class VerificationError(IRError): pass class MacroError(NumbaError): \"\"\" An error occurred during macro expansion.", "# Simply emit other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self): \"\"\"", "# Store warnings of this category for deduplication filename = filename or w.filename", "print_function, division, absolute_import import contextlib from collections import defaultdict import warnings # Filled", "\"\"\" Emit all stored warnings. \"\"\" for (filename, lineno, category), messages in sorted(self._warnings.items()):", "lineno, category), messages in sorted(self._warnings.items()): for msg in sorted(messages): warnings.warn_explicit(msg, category, filename, lineno)", "or w.filename lineno = lineno or w.lineno self._warnings[filename, lineno, w.category].add(msg) else: # Simply", "lineno=None): \"\"\" Store warnings and optionally fix their filename and lineno. \"\"\" with", "warnings and optionally fix their filename and lineno. \"\"\" with warnings.catch_warnings(record=True) as wlist:", "import defaultdict import warnings # Filled at the end __all__ = [] class", "Filled at the end __all__ = [] class NumbaWarning(Warning): \"\"\" Base category for", "self.loc = loc def __str__(self): loc = \"?\" if self.loc is None else", "loc=loc) class ByteCodeSupportError(NumbaError): \"\"\" Failure to extract the bytecode of the user's function.", "loc: super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError):", "collections import defaultdict import warnings # Filled at the end __all__ = []", "(msg,)) class UntypedAttributeError(TypingError): def __init__(self, value, attr, loc=None): msg = 'Unknown attribute \"{attr}\"", "fixed, and they are deduplicated as well. \"\"\" def __init__(self, category): self._category =", "self._category) yield for w in wlist: msg = str(w.message) if issubclass(w.category, self._category): #", "super(TypingError, self).__init__(\"%s\\n%s\" % (msg, loc.strformat())) else: super(TypingError, self).__init__(\"%s\" % (msg,)) class UntypedAttributeError(TypingError): def", "\"\"\" An error occurred during macro expansion. \"\"\" class DeprecationError(NumbaError): pass class LoweringError(NumbaError):", "NotDefinedError(IRError): def __init__(self, name, loc=None): self.name = name self.loc = loc def __str__(self):", "pass class LoweringError(NumbaError): \"\"\" An error occurred during lowering. \"\"\" def __init__(self, msg,", "be as fast as expected. \"\"\" class WarningsFixer(object): \"\"\" An object \"fixing\" warnings", "__str__(self): loc = \"?\" if self.loc is None else self.loc return \"{name!r} is", "else: # Simply emit other warnings again warnings.warn_explicit(msg, w.category, w.filename, w.lineno) def flush(self):" ]
[ "change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key, value) try:", "agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass", "not None: tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for", "value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key in keys: agent.set_tag(key, \"\")", "value) def remove_tags(*keys): for key in keys: agent.set_tag(key, \"\") def build_summary(): return agent.build_summary()", "tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value", "stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value in tags.items():", "class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address,", "tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key, value in tags.items(): agent.set_tag(key, value) def", "key in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key, value in tags.items(): agent.set_tag(key,", "finally: for key in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key, value in", "key, value in tags.items(): agent.set_tag(key, value) try: yield finally: for key in tags.keys():", "@contextmanager def tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key, value) try: yield finally:", "def remove_tags(*keys): for key in keys: agent.set_tag(key, \"\") def build_summary(): return agent.build_summary() def", "'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name,", "'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0,", "contextlib import contextmanager from pyroscope import agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token',", "namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address,", "tag(tags): for key, value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key in", "auth_token, sample_rate, int(with_subprocesses), log_level) if tags is not None: tag(tags) def stop(): agent.stop()", "try: yield finally: for key in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key,", "agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key,", "import agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception):", "is not None: tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags):", "key, value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key in keys: agent.set_tag(key,", "= namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name,", "agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags is not None: tag(tags) def", "tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key, value) try: yield finally: for key", "\"\") def tag(tags): for key, value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for", "collections import namedtuple from contextlib import contextmanager from pyroscope import agent Config =", "from collections import namedtuple from contextlib import contextmanager from pyroscope import agent Config", "yield finally: for key in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key, value", "from contextlib import contextmanager from pyroscope import agent Config = namedtuple('Config', ('app_name', 'server_address',", "def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key, value)", "'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100,", "import namedtuple from contextlib import contextmanager from pyroscope import agent Config = namedtuple('Config',", "tags.items(): agent.set_tag(key, value) try: yield finally: for key in tags.keys(): agent.set_tag(key, \"\") def", "log_level) if tags is not None: tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name)", "in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key in keys: agent.set_tag(key, \"\") def", "int(with_subprocesses), log_level) if tags is not None: tag(tags) def stop(): agent.stop() def change_name(name):", "PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token,", "def tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key, value) try: yield finally: for", "tags is not None: tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def", "pyroscope import agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class", "with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags is not", "if tags is not None: tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager", "namedtuple from contextlib import contextmanager from pyroscope import agent Config = namedtuple('Config', ('app_name',", "None: tag(tags) def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key,", "tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key in keys: agent.set_tag(key, \"\") def build_summary():", "in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key, value in tags.items(): agent.set_tag(key, value)", "value in tags.items(): agent.set_tag(key, value) try: yield finally: for key in tags.keys(): agent.set_tag(key,", "agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value in tags.items(): agent.set_tag(key, value) try: yield", "Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def", "pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate,", "for key, value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key in keys:", "server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if", "def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses),", "'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\",", "value) try: yield finally: for key in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for", "agent.set_tag(key, value) def remove_tags(*keys): for key in keys: agent.set_tag(key, \"\") def build_summary(): return", "sample_rate, int(with_subprocesses), log_level) if tags is not None: tag(tags) def stop(): agent.stop() def", "import contextmanager from pyroscope import agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate',", "contextmanager from pyroscope import agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses',", "def tag(tags): for key, value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys): for key", "from pyroscope import agent Config = namedtuple('Config', ('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level'))", "in tags.items(): agent.set_tag(key, value) try: yield finally: for key in tags.keys(): agent.set_tag(key, \"\")", "log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags is not None:", "remove_tags(*keys): for key in keys: agent.set_tag(key, \"\") def build_summary(): return agent.build_summary() def test_logger():", "server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags is not None: tag(tags) def stop():", "auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags", "def stop(): agent.stop() def change_name(name): agent.change_name(name) @contextmanager def tag_wrapper(tags): for key, value in", "for key in tags.keys(): agent.set_tag(key, \"\") def tag(tags): for key, value in tags.items():", "'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None):", "configure(app_name, server_address, auth_token=\"\", sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level)", "for key, value in tags.items(): agent.set_tag(key, value) try: yield finally: for key in", "for key in keys: agent.set_tag(key, \"\") def build_summary(): return agent.build_summary() def test_logger(): agent.test_logger()", "('app_name', 'server_address', 'auth_token', 'sample_rate', 'with_subprocesses', 'log_level')) class PyroscopeError(Exception): pass def configure(app_name, server_address, auth_token=\"\",", "agent.set_tag(key, \"\") def tag(tags): for key, value in tags.items(): agent.set_tag(key, value) def remove_tags(*keys):", "tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags is not None: tag(tags)", "sample_rate=100, with_subprocesses=0, log_level=\"debug\", tags=None): agent.start(app_name, server_address, auth_token, sample_rate, int(with_subprocesses), log_level) if tags is", "agent.set_tag(key, value) try: yield finally: for key in tags.keys(): agent.set_tag(key, \"\") def tag(tags):" ]
[ "Loops/08. Number sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input()) for i in range(count_of_nums):", "sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input()) for i in range(count_of_nums): n =", "i in range(count_of_nums): n = int(input()) numbers.append(n) print(f'Max number: {max(numbers)}') print(f'Min number: {min(numbers)}')", "Essentials/04. For Loops/08. Number sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input()) for i", "For Loops/08. Number sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input()) for i in", "<filename>06. Python Essentials/04. For Loops/08. Number sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input())", "int(input()) for i in range(count_of_nums): n = int(input()) numbers.append(n) print(f'Max number: {max(numbers)}') print(f'Min", "numbers = [] count_of_nums = int(input()) for i in range(count_of_nums): n = int(input())", "= [] count_of_nums = int(input()) for i in range(count_of_nums): n = int(input()) numbers.append(n)", "= int(input()) for i in range(count_of_nums): n = int(input()) numbers.append(n) print(f'Max number: {max(numbers)}')", "Python Essentials/04. For Loops/08. Number sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input()) for", "Number sequence.py<gh_stars>0 numbers = [] count_of_nums = int(input()) for i in range(count_of_nums): n", "[] count_of_nums = int(input()) for i in range(count_of_nums): n = int(input()) numbers.append(n) print(f'Max", "count_of_nums = int(input()) for i in range(count_of_nums): n = int(input()) numbers.append(n) print(f'Max number:", "for i in range(count_of_nums): n = int(input()) numbers.append(n) print(f'Max number: {max(numbers)}') print(f'Min number:" ]
[ "shine. And on leap years, twenty-nine. A leap year occurs on any year", "year % 4 == 0: return 29 else: return 28 else: return 31", "month == 11: return 30 elif month == 2: if year % 4", "return days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays =", "Saving February alone, Which has twenty-eight, rain or shine. And on leap years,", "6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0 for year in range(1901,", "the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?", "1901 is Jan 6 return days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days", "evenly divisible by 4, but not on a century unless it is divisible", "month == 9 or month == 11: return 30 elif month == 2:", "month): if month == 4 or month == 6 or month == 9", "def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0 for year in range(1901, 2001):", "2000)? \"\"\" def days_in(year, month): if month == 4 or month == 6", "or month == 11: return 30 elif month == 2: if year %", "6 return days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays", "thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap", "== 9 or month == 11: return 30 elif month == 2: if", "month == 4 or month == 6 or month == 9 or month", "if month == 4 or month == 6 or month == 9 or", "1st sunday in 1901 is Jan 6 return days_post_jan_1_1901 % 7 == 6", "in 1901 is Jan 6 return days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000():", "Monday. Thirty days has September, April, June and November. All the rest have", "month == 2: if year % 4 == 0: return 29 else: return", "1901 to 31 Dec 2000)? \"\"\" def days_in(year, month): if month == 4", "days_in(year, month): if month == 4 or month == 6 or month ==", "6 or month == 9 or month == 11: return 30 elif month", "and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight,", "it is divisible by 400. How many Sundays fell on the first of", "rain or shine. And on leap years, twenty-nine. A leap year occurs on", "month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? \"\"\"", "is divisible by 400. How many Sundays fell on the first of the", "month == 6 or month == 9 or month == 11: return 30", "on a century unless it is divisible by 400. How many Sundays fell", "(1 Jan 1901 to 31 Dec 2000)? \"\"\" def days_in(year, month): if month", "def days_in(year, month): if month == 4 or month == 6 or month", "for year in range(1901, 2001): for month in range(1, 13): total_days += days_in(year,", "is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is Jan 6 return days_post_jan_1_1901 % 7", "else: return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is Jan 6", "on leap years, twenty-nine. A leap year occurs on any year evenly divisible", "on the first of the month during the twentieth century (1 Jan 1901", "or month == 9 or month == 11: return 30 elif month ==", "How many Sundays fell on the first of the month during the twentieth", "Jan 1901 to 31 Dec 2000)? \"\"\" def days_in(year, month): if month ==", "def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is Jan 6 return days_post_jan_1_1901 %", "== 0: return 29 else: return 28 else: return 31 def is_sunday(days_post_jan_1_1901): #", "years, twenty-nine. A leap year occurs on any year evenly divisible by 4,", "twentieth century (1 Jan 1901 to 31 Dec 2000)? \"\"\" def days_in(year, month):", "== 2: if year % 4 == 0: return 29 else: return 28", "year occurs on any year evenly divisible by 4, but not on a", "or shine. And on leap years, twenty-nine. A leap year occurs on any", "February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine.", "divisible by 4, but not on a century unless it is divisible by", "return 28 else: return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is", "month in range(1, 13): total_days += days_in(year, month) if is_sunday(total_days): sundays +=1 return", "# 1st sunday in 1901 is Jan 6 return days_post_jan_1_1901 % 7 ==", "but not on a century unless it is divisible by 400. How many", "on any year evenly divisible by 4, but not on a century unless", "range(1901, 2001): for month in range(1, 13): total_days += days_in(year, month) if is_sunday(total_days):", "for month in range(1, 13): total_days += days_in(year, month) if is_sunday(total_days): sundays +=1", "rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And", "2: if year % 4 == 0: return 29 else: return 28 else:", "occurs on any year evenly divisible by 4, but not on a century", "sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0 for year in range(1901, 2001): for", "a century unless it is divisible by 400. How many Sundays fell on", "sundays = 0 for year in range(1901, 2001): for month in range(1, 13):", "first of the month during the twentieth century (1 Jan 1901 to 31", "the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine.", "leap years, twenty-nine. A leap year occurs on any year evenly divisible by", "4 == 0: return 29 else: return 28 else: return 31 def is_sunday(days_post_jan_1_1901):", "has September, April, June and November. All the rest have thirty-one, Saving February", "of the month during the twentieth century (1 Jan 1901 to 31 Dec", "by 4, but not on a century unless it is divisible by 400.", "has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year", "during the twentieth century (1 Jan 1901 to 31 Dec 2000)? \"\"\" def", "return 30 elif month == 2: if year % 4 == 0: return", "\"\"\" def days_in(year, month): if month == 4 or month == 6 or", "return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is Jan 6 return", "== 6 or month == 9 or month == 11: return 30 elif", "year evenly divisible by 4, but not on a century unless it is", "to 31 Dec 2000)? \"\"\" def days_in(year, month): if month == 4 or", "alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A", "All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or", "unless it is divisible by 400. How many Sundays fell on the first", "the first of the month during the twentieth century (1 Jan 1901 to", "Jan 1900 was a Monday. Thirty days has September, April, June and November.", "= 1 sundays = 0 for year in range(1901, 2001): for month in", "Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap", "in range(1901, 2001): for month in range(1, 13): total_days += days_in(year, month) if", "fell on the first of the month during the twentieth century (1 Jan", "have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on", "total_days = 1 sundays = 0 for year in range(1901, 2001): for month", "1900 was a Monday. Thirty days has September, April, June and November. All", "Dec 2000)? \"\"\" def days_in(year, month): if month == 4 or month ==", "in range(1, 13): total_days += days_in(year, month) if is_sunday(total_days): sundays +=1 return sundays", "31 Dec 2000)? \"\"\" def days_in(year, month): if month == 4 or month", "century (1 Jan 1901 to 31 Dec 2000)? \"\"\" def days_in(year, month): if", "is Jan 6 return days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days =", "== 11: return 30 elif month == 2: if year % 4 ==", "= 0 for year in range(1901, 2001): for month in range(1, 13): total_days", "century unless it is divisible by 400. How many Sundays fell on the", "not on a century unless it is divisible by 400. How many Sundays", "% 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0 for", "was a Monday. Thirty days has September, April, June and November. All the", "400. How many Sundays fell on the first of the month during the", "twenty-nine. A leap year occurs on any year evenly divisible by 4, but", "a Monday. Thirty days has September, April, June and November. All the rest", "if year % 4 == 0: return 29 else: return 28 else: return", "7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0 for year", "leap year occurs on any year evenly divisible by 4, but not on", "twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs", "Jan 6 return days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1", "29 else: return 28 else: return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday in", "0 for year in range(1901, 2001): for month in range(1, 13): total_days +=", "And on leap years, twenty-nine. A leap year occurs on any year evenly", "Thirty days has September, April, June and November. All the rest have thirty-one,", "11: return 30 elif month == 2: if year % 4 == 0:", "year in range(1901, 2001): for month in range(1, 13): total_days += days_in(year, month)", "days_post_jan_1_1901 % 7 == 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0", "== 6 def sunday_as_first_of_month_from_1901_2000(): total_days = 1 sundays = 0 for year in", "by 400. How many Sundays fell on the first of the month during", "1 sundays = 0 for year in range(1901, 2001): for month in range(1,", "April, June and November. All the rest have thirty-one, Saving February alone, Which", "September, April, June and November. All the rest have thirty-one, Saving February alone,", "9 or month == 11: return 30 elif month == 2: if year", "days has September, April, June and November. All the rest have thirty-one, Saving", "30 elif month == 2: if year % 4 == 0: return 29", "A leap year occurs on any year evenly divisible by 4, but not", "4 or month == 6 or month == 9 or month == 11:", "or month == 6 or month == 9 or month == 11: return", "many Sundays fell on the first of the month during the twentieth century", "2001): for month in range(1, 13): total_days += days_in(year, month) if is_sunday(total_days): sundays", "divisible by 400. How many Sundays fell on the first of the month", "else: return 28 else: return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901", "June and November. All the rest have thirty-one, Saving February alone, Which has", "1 Jan 1900 was a Monday. Thirty days has September, April, June and", "% 4 == 0: return 29 else: return 28 else: return 31 def", "4, but not on a century unless it is divisible by 400. How", "<reponame>piohhmy/euler \"\"\" 1 Jan 1900 was a Monday. Thirty days has September, April,", "elif month == 2: if year % 4 == 0: return 29 else:", "Sundays fell on the first of the month during the twentieth century (1", "the twentieth century (1 Jan 1901 to 31 Dec 2000)? \"\"\" def days_in(year,", "sunday in 1901 is Jan 6 return days_post_jan_1_1901 % 7 == 6 def", "any year evenly divisible by 4, but not on a century unless it", "return 29 else: return 28 else: return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday", "November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain", "== 4 or month == 6 or month == 9 or month ==", "\"\"\" 1 Jan 1900 was a Monday. Thirty days has September, April, June", "28 else: return 31 def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is Jan", "31 def is_sunday(days_post_jan_1_1901): # 1st sunday in 1901 is Jan 6 return days_post_jan_1_1901", "0: return 29 else: return 28 else: return 31 def is_sunday(days_post_jan_1_1901): # 1st" ]
[ "bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"],", "from discord.ext import commands from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date class", "commands from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog): def __init__(self,bot):", "-1 if none are valid ''' for id,addArray in self.exchangeNames.items(): if address in", "fromID == -1: await ctx.send(\"Was unable to find currency for {}\".format(fromAddress)) elif toID", "\"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"],", "Gets exchange rate from between two currencies. $ExchangeRate USD to JPY => The", "fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was unable", "rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address name for", "import commands from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog): def", "letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID)", "''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip()", "discord.ext import commands from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog):", "\"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command()", "\"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"],", "lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary", "discord from discord.ext import commands from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date", "exchange rate from between two currencies. $ExchangeRate USD to JPY => The exchange", "ctx.send(\"Was unable to find currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The", "krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden", "south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand", "self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was", "\"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"],", "koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates =", "kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"],", "dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico", "peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async", "from datetime import date class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames =", "CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange rate from", "between two currencies. $ExchangeRate USD to JPY => The exchange rate from USD", "\"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New", "for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1 is", "find currency for {}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was unable to find", "= self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1: await", "\"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"],", "unable to find currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange", "from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address name for desired", "''' for id,addArray in self.exchangeNames.items(): if address in addArray: return id return -1", "returns the id of the desired currency or -1 if none are valid", "__init__(self,bot): self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria", "\"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic", "= letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode =", "import CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot", "New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"],", "toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was unable to find currency", "to JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters =", "import discord from discord.ext import commands from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import", "JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\")", "fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode", "is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address name for desired currency address", "is the name of the desired currency returns the id of the desired", "of the desired currency returns the id of the desired currency or -1", "self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was unable to find", "\"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia", "yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states", "letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress)", "of the desired currency or -1 if none are valid ''' for id,addArray", "self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange rate from between", "= CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange rate", "Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland", "\"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"],", "datetime import date class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames = {", "USD to JPY => The exchange rate from USD to JPY is xxx.xx", "\"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"],", "republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates", "= letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode =", "krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland", "valid ''' for id,addArray in self.exchangeNames.items(): if address in addArray: return id return", "{ \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"],", "real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes", "letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress", "{}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was unable to find currency for {}\".format(toAddress))", "xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\") fromAddress =", "letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID)", "zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"],", "rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address):", "\"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand", "in self.exchangeNames.items(): if address in addArray: return id return -1 def setup(bot): bot.add_cog(Exchange(bot))", "the id of the desired currency or -1 if none are valid '''", "for id,addArray in self.exchangeNames.items(): if address in addArray: return id return -1 def", "await ctx.send(\"Was unable to find currency for {}\".format(fromAddress)) elif toID == -1: await", "africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx):", "the name of the desired currency returns the id of the desired currency", "self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the", "import date class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro", "from forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog): def __init__(self,bot): self.bot", "franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new", "\"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"],", "\"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"],", "class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"],", "lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"],", "def ExchangeRate(self,ctx): ''' Gets exchange rate from between two currencies. $ExchangeRate USD to", "\"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"],", "\"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"],", "= letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID =", "letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID", "pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia", "to find currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate", "two currencies. $ExchangeRate USD to JPY => The exchange rate from USD to", "if none are valid ''' for id,addArray in self.exchangeNames.items(): if address in addArray:", "\"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia", "= ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress =", "\"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes =", "exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address name", "from between two currencies. $ExchangeRate USD to JPY => The exchange rate from", "are valid ''' for id,addArray in self.exchangeNames.items(): if address in addArray: return id", "kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"],", "rate from USD to JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters =", "def getAddressName(self,address): '''Gets the proper address name for desired currency address is the", "= bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel", "= CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange rate from between two", "name for desired currency address is the name of the desired currency returns", "-1: await ctx.send(\"Was unable to find currency for {}\".format(fromAddress)) elif toID == -1:", "= letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID =", "''' Gets exchange rate from between two currencies. $ExchangeRate USD to JPY =>", "\"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"],", "kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"],", "{}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate))", "krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south", "currency address is the name of the desired currency returns the id of", "rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan", "currencies. $ExchangeRate USD to JPY => The exchange rate from USD to JPY", "or -1 if none are valid ''' for id,addArray in self.exchangeNames.items(): if address", "the desired currency or -1 if none are valid ''' for id,addArray in", "baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech", "\"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong", "@commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange rate from between two currencies. $ExchangeRate", "shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania", "\"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united", "forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"],", "self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange", "CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets exchange rate from between two currencies.", "the proper address name for desired currency address is the name of the", "Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia", "dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia", "desired currency returns the id of the desired currency or -1 if none", "exchange rate from USD to JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters", "member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"],", "dollar\"], \"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore", "date class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member", "= self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets", "= self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID", "{}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address name for desired currency address is", "ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines", "self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was unable to find currency for {}\".format(fromAddress))", "toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode", "\"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa", "USD to JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters", "{}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address name for desired currency", "self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united", "\"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway", "else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def", "async def ExchangeRate(self,ctx): ''' Gets exchange rate from between two currencies. $ExchangeRate USD", "from USD to JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower()", "yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong", "letters = letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID", "unable to find currency for {}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was unable", "for {}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was unable to find currency for", "address name for desired currency address is the name of the desired currency", "desired currency or -1 if none are valid ''' for id,addArray in self.exchangeNames.items():", "ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south", "= self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was unable to find currency for", "toID == -1: await ctx.send(\"Was unable to find currency for {}\".format(toAddress)) else: rate", "countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark krone\"], \"CAD\":[\"cad\",\"canada", "won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"],", "= { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom", "== -1: await ctx.send(\"Was unable to find currency for {}\".format(toAddress)) else: rate =", "for desired currency address is the name of the desired currency returns the", "\"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def", "proper address name for desired currency address is the name of the desired", "await ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper", "address is the name of the desired currency returns the id of the", "currency or -1 if none are valid ''' for id,addArray in self.exchangeNames.items(): if", "won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"],", "\"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] }", "$ExchangeRate USD to JPY => The exchange rate from USD to JPY is", "none are valid ''' for id,addArray in self.exchangeNames.items(): if address in addArray: return", "The exchange rate from USD to JPY is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1]", "\"JPY\":[\"jpy\",\"japan yen\"], \"HUF\":[\"huf\",\"hungary forint\"], \"RON\":[\"ron\",\"Romania New Leu\"], \"MYR\":[\"myr\",\"malaysia ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"],", "CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog): def __init__(self,bot): self.bot = bot self.exchangeNames", "=> The exchange rate from USD to JPY is xxx.xx ''' letters =", "self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID ==", "toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1:", "JPY => The exchange rate from USD to JPY is xxx.xx ''' letters", "id of the desired currency or -1 if none are valid ''' for", "\"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"],", "'''Gets the proper address name for desired currency address is the name of", "the desired currency returns the id of the desired currency or -1 if", "dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey", "letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip() fromID = self.getAddressName(fromAddress)", "zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes()", "is xxx.xx ''' letters = ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\") fromAddress", "\"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea", "find currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from", "\"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india", "desired currency address is the name of the desired currency returns the id", "states dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"],", "ExchangeRate(self,ctx): ''' Gets exchange rate from between two currencies. $ExchangeRate USD to JPY", "rand\"] } self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): '''", "forex_python.converter import CurrencyRates,CurrencyCodes from datetime import date class Exchange(commands.Cog): def __init__(self,bot): self.bot =", "} self.CurrencyRates = CurrencyRates() self.CurrencyCodes = CurrencyCodes() @commands.command() async def ExchangeRate(self,ctx): ''' Gets", "dollar\"], \"NOK\":[\"nok\",\"norway krone\"], \"RUB\":[\"rub\",\"russia ruble\"], \"INR\":[\"inr\",\"india ruppe\"], \"MXN\":[\"mxn\",\"mexico peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil", "if fromID == -1: await ctx.send(\"Was unable to find currency for {}\".format(fromAddress)) elif", "to find currency for {}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was unable to", "await ctx.send(\"Was unable to find currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await", "ctx.send(\"The exchange rate from {}1 is {}{:.2f}\".format(fromCode,toCode,rate)) def getAddressName(self,address): '''Gets the proper address", "-1: await ctx.send(\"Was unable to find currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID)", "renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"], \"NZD\":[\"nzd\",\"new zealand dollar\"], \"THB\":[\"thb\",\"thailand baht\"], \"USD\":[\"usd\",\"united states dollar\"],", "\"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"], \"ILS\":[\"ils\",\"israel shekel\"], \"GBP\":[\"gbp\",\"united kingdom pound\"], \"DKK\":[\"dkk\",\"denmark", "getAddressName(self,address): '''Gets the proper address name for desired currency address is the name", "id,addArray in self.exchangeNames.items(): if address in addArray: return id return -1 def setup(bot):", "fromID = self.getAddressName(fromAddress) toID = self.getAddressName(toAddress) fromCode = self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if", "\"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun", "ctx.message.content.split(maxsplit=1)[1] letters = letters.lower() letters = letters.split(\"to\") fromAddress = letters[0].strip() toAddress = letters[1].strip()", "elif toID == -1: await ctx.send(\"Was unable to find currency for {}\".format(toAddress)) else:", "def __init__(self,bot): self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"],", "name of the desired currency returns the id of the desired currency or", "currency returns the id of the desired currency or -1 if none are", "self.bot = bot self.exchangeNames = { \"EUR\":[\"eur\",\"euro member countries\"], \"IDR\":[\"idr\",\"indonesia rupiah\"], \"BGN\":[\"bgn\",\"bulgaria lev\"],", "\"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"] } self.CurrencyRates = CurrencyRates()", "ctx.send(\"Was unable to find currency for {}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was", "= self.CurrencyCodes.get_symbol(fromID) toCode = self.CurrencyCodes.get_symbol(toID) if fromID == -1: await ctx.send(\"Was unable to", "rate from between two currencies. $ExchangeRate USD to JPY => The exchange rate", "to JPY => The exchange rate from USD to JPY is xxx.xx '''", "\"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china yun renminbi\"], \"TRY\":[\"try\",\"turkey lira\"], \"HRK\":[\"hrk\",\"croatia kuna\"],", "== -1: await ctx.send(\"Was unable to find currency for {}\".format(fromAddress)) elif toID ==", "currency for {}\".format(fromAddress)) elif toID == -1: await ctx.send(\"Was unable to find currency", "ringgit\"], \"SEK\":[\"sek\",\"sweden krona\"], \"SGD\":[\"sgd\",\"singapore dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea", "dollar\"], \"HKD\":[\"hkd\",\"hong kong dollar\"], \"AUD\":[\"aud\",\"australia dollar\"], \"CHF\":[\"chf\",\"switzerland franc\"], \"KRW\":[\"krw\",\"korea won\",\"korea south won\"], \"CNY\":[\"cny\",\"china", "currency for {}\".format(toAddress)) else: rate = self.CurrencyRates.get_rate(fromID,toID) await ctx.send(\"The exchange rate from {}1", "peso\"], \"CZK\":[\"czh\",\"czech republic koruna\"], \"BRL\":[\"brl\",\"brazil real\"], \"PLN\":[\"pln\",\"poland zloty\"], \"PHP\":[\"php\",\"philippines peso\"], \"ZAR\":[\"zar\",\"south africa rand\"]" ]
[ "<reponame>mmechelke/bayesian_xfel import unittest from bxfel.orientation.quadrature import GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class", "= GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0],", "as np class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is", "is not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self):", "self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for", "i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) if", "np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def", "R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m,", "class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None)", "g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w is not None)", "def test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R),", "test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.)", "GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25)", "g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R", "0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R", "g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) if __name__ == \"__main__\":", "None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i)", "self.assertTrue(g._R is not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def", "for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1)", "np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) if __name__ ==", "self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is", "= GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g", "np class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not", "is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g", "import unittest from bxfel.orientation.quadrature import GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase):", "g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self):", "= np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase):", "np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R:", "in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4)", "= GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) if __name__ == \"__main__\": unittest.main()", "ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m,", "import numpy as np class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4)", "1.) class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not", "def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w is", "unittest from bxfel.orientation.quadrature import GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase): def", "not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i", "= np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) if __name__", "GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1)", "import GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase): def test_init(self): g =", "GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class TestGauss(unittest.TestCase): def test_init(self): g =", "TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w", "i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in g._R: self.assertAlmostEqual(np.linalg.det(R), 1.) class", "numpy as np class TestGauss(unittest.TestCase): def test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R", "test_init(self): g = GaussSO3Quadrature(1) self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w is not", "bxfel.orientation.quadrature import GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase): def test_init(self): g", "4) self.assertTrue(g._R is not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel()))", "None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i =", "not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g =", "from bxfel.orientation.quadrature import GaussSO3Quadrature, ChebyshevSO3Quadrature import numpy as np class TestGauss(unittest.TestCase): def test_init(self):", "self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10) g = GaussSO3Quadrature(i) for R in", "self.assertEqual(g.m, 4) self.assertTrue(g._R is not None) self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(),", "self.assertTrue(g._w is not None) self.assertEqual(g._w[0], 0.25) self.assertTrue(np.array_equal(g._R[0].ravel(), np.eye(3).ravel())) def test_Rotation(self): i = np.random.randint(1,10)" ]
[ "nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep = nms(pred_boxes, scores, nms_thresh) return", "details] # Written by <NAME> # -------------------------------------------------------- import torch from torchvision.ops import nms", "Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License", "R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see", "(c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details]", "scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep = nms(pred_boxes, scores, nms_thresh)", "<NAME> # -------------------------------------------------------- import torch from torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh):", "LICENSE for details] # Written by <NAME> # -------------------------------------------------------- import torch from torchvision.ops", "# Licensed under The MIT License [see LICENSE for details] # Written by", "Written by <NAME> # -------------------------------------------------------- import torch from torchvision.ops import nms def nms_detections(pred_boxes,", "by <NAME> # -------------------------------------------------------- import torch from torchvision.ops import nms def nms_detections(pred_boxes, scores,", "<reponame>songheony/MOTDT<filename>utils/nms_wrapper.py # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed", "import torch from torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes)", "pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep = nms(pred_boxes, scores, nms_thresh) return keep", "import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep", "under The MIT License [see LICENSE for details] # Written by <NAME> #", "for details] # Written by <NAME> # -------------------------------------------------------- import torch from torchvision.ops import", "MIT License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- import", "torch from torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores", "# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under", "nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep =", "-------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The", "The MIT License [see LICENSE for details] # Written by <NAME> # --------------------------------------------------------", "[see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- import torch from", "-------------------------------------------------------- import torch from torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes =", "# -------------------------------------------------------- import torch from torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes", "Microsoft # Licensed under The MIT License [see LICENSE for details] # Written", "from torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores =", "# Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT", "torchvision.ops import nms def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores)", "nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep = nms(pred_boxes, scores,", "Licensed under The MIT License [see LICENSE for details] # Written by <NAME>", "Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for", "# Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE", "License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- import torch", "2015 Microsoft # Licensed under The MIT License [see LICENSE for details] #", "def nms_detections(pred_boxes, scores, nms_thresh): pred_boxes = torch.FloatTensor(pred_boxes) scores = torch.FloatTensor(scores) keep = nms(pred_boxes,", "# Written by <NAME> # -------------------------------------------------------- import torch from torchvision.ops import nms def" ]
[ "class Metric: def initialize(self): pass def log_batch(self, predicted, ground_truth): pass def compute(self): pass", "<gh_stars>0 class Metric: def initialize(self): pass def log_batch(self, predicted, ground_truth): pass def compute(self):" ]
[ "TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def", "else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return", "return self.__stop_time def lap(self): lap_end_time = self._now lap_start_time = (self.__start_time if not self.__laps", "lap_start_time = (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time,", "def lap(self): lap_end_time = self._now lap_start_time = (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time'])", "logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time =", "from .timeout import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch,", "if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time -", "self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time })", "self.__laps = [] self.__start_time = self._now def stop(self): if self.__stop_time is None: self.__stop_time", "None self.__laps = [] self.__start_time = self._now def stop(self): if self.__stop_time is None:", "self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time']", "not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time", "return self.__laps @property def glance(self): if self.__stop_time: return self.__stop_time - self.__start_time else: return", "self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None self.__laps = [] self.__start_time = self._now", "@property def lap_times(self): return self.__laps @property def glance(self): if self.__stop_time: return self.__stop_time -", "logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self):", "self._now return self.glance else: return self.__stop_time def lap(self): lap_end_time = self._now lap_start_time =", "# encoding: utf-8 import logging_helper from .timeout import TimersBase logging = logging_helper.setup_logging() class", "def stop(self): if self.__stop_time is None: self.__stop_time = self._now return self.glance else: return", "self.__stop_time = None self.__laps = [] self.__start_time = self._now def stop(self): if self.__stop_time", "class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None", "}) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property def glance(self): if self.__stop_time:", "self.reset() def reset(self): self.__stop_time = None self.__laps = [] self.__start_time = self._now def", "logging_helper from .timeout import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None):", "if self.__stop_time is None: self.__stop_time = self._now return self.glance else: return self.__stop_time def", "None: self.__stop_time = self._now return self.glance else: return self.__stop_time def lap(self): lap_end_time =", "self._now def stop(self): if self.__stop_time is None: self.__stop_time = self._now return self.glance else:", "self._now lap_start_time = (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time':", "self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property", "= [] self.__start_time = self._now def stop(self): if self.__stop_time is None: self.__stop_time =", "= None self.__laps = [] self.__start_time = self._now def stop(self): if self.__stop_time is", "self.__stop_time = self._now return self.glance else: return self.__stop_time def lap(self): lap_end_time = self._now", "lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property def glance(self): if", "[] self.__start_time = self._now def stop(self): if self.__stop_time is None: self.__stop_time = self._now", "def lap_times(self): return self.__laps @property def glance(self): if self.__stop_time: return self.__stop_time - self.__start_time", "encoding: utf-8 import logging_helper from .timeout import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase):", "self.glance else: return self.__stop_time def lap(self): lap_end_time = self._now lap_start_time = (self.__start_time if", "high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None self.__laps = [] self.__start_time", "reset(self): self.__stop_time = None self.__laps = [] self.__start_time = self._now def stop(self): if", "lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps", "Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None self.__laps", "def reset(self): self.__stop_time = None self.__laps = [] self.__start_time = self._now def stop(self):", "= (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time':", "lap(self): lap_end_time = self._now lap_start_time = (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({", "u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return", "__init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None self.__laps = []", "import logging_helper from .timeout import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self,", "super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None self.__laps = [] self.__start_time =", "def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time = None self.__laps =", "self.__start_time = self._now def stop(self): if self.__stop_time is None: self.__stop_time = self._now return", "= self._now return self.glance else: return self.__stop_time def lap(self): lap_end_time = self._now lap_start_time", "u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property def", "= logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset() def reset(self): self.__stop_time", "return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property def glance(self): if self.__stop_time: return", "= self._now def stop(self): if self.__stop_time is None: self.__stop_time = self._now return self.glance", "self.__stop_time is None: self.__stop_time = self._now return self.glance else: return self.__stop_time def lap(self):", "lap_times(self): return self.__laps @property def glance(self): if self.__stop_time: return self.__stop_time - self.__start_time else:", "- lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property def glance(self):", "self.__laps @property def glance(self): if self.__stop_time: return self.__stop_time - self.__start_time else: return self._now", "else: return self.__stop_time def lap(self): lap_end_time = self._now lap_start_time = (self.__start_time if not", "lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property def", ".timeout import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision)", "return self.glance else: return self.__stop_time def lap(self): lap_end_time = self._now lap_start_time = (self.__start_time", "is None: self.__stop_time = self._now return self.glance else: return self.__stop_time def lap(self): lap_end_time", "= self._now lap_start_time = (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time,", "@property def glance(self): if self.__stop_time: return self.__stop_time - self.__start_time else: return self._now -", "import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def __init__(self, high_precision=None): super(Stopwatch, self).__init__(high_precision=high_precision) self.reset()", "u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property", "self.__laps[-1][u'lap_time'] @property def lap_times(self): return self.__laps @property def glance(self): if self.__stop_time: return self.__stop_time", "utf-8 import logging_helper from .timeout import TimersBase logging = logging_helper.setup_logging() class Stopwatch(TimersBase): def", "lap_end_time = self._now lap_start_time = (self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time':", "lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time - lap_start_time }) return self.__laps[-1][u'lap_time'] @property def lap_times(self):", "stop(self): if self.__stop_time is None: self.__stop_time = self._now return self.glance else: return self.__stop_time", "def glance(self): if self.__stop_time: return self.__stop_time - self.__start_time else: return self._now - self.__start_time", "(self.__start_time if not self.__laps else self.__laps[-1][u'lap_end_time']) self.__laps.append({ u'lap_start_time': lap_start_time, u'lap_end_time': lap_end_time, u'lap_time': lap_end_time", "self.__stop_time def lap(self): lap_end_time = self._now lap_start_time = (self.__start_time if not self.__laps else" ]
[ "except Exception as e: return timeout, f'failed to resolve domain, {e}' data_type =", "struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello, world!' sock.send(packet) print(packet) #", "not None for item in self._q) def failure_ratio(self): total = self.total() if total", "def chesksum(data): n = len(data) m = n % 2 sum_ = 0", "time.time() - t0 if time_elapsed >= timeout: return timeout, 'timeout' rlist, _, _", "self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q) # def success(self): # return sum(err", "b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close()", "1) % 0xffff stat.update((time_elapsed, err)) total = stat.total() fail = stat.failure() print('total:', total,", "= socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed, err = _ping_once(rawsocket,", "'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header, ip_payload =", "[], timeout - time_elapsed) if len(rlist) == 0: return timeout, 'timeout' data, _", "play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header", "addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence + 1) % 0xffff stat.update((time_elapsed, err))", "0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum,", "PingStat(MovingStatistic): def total(self): return len(self._q) # def success(self): # return sum(err is None", "self._q.append(TimedData(data, now)) while len(self._q) > 0 and now - self._q[0].ts > self._duration: self._q.popleft()", "length == 0: return b'' n = (length // 16) + 1 if", "else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id,", "(i + 1 - accept) / (i + 1) * 100, shorttime, longtime,", "def __init__(self, data, ts): self.data = data self.ts = ts class MovingStatistic: def", "t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload)", "# 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 | (answer << 8 & 0xff00)", "accept, i + 1 - accept, (i + 1 - accept) / (i", "return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat", "n = len(data) m = n % 2 sum_ = 0 for i", "= duration self._q = deque() def update(self, data): now = time.time() self._q.append(TimedData(data, now))", "class TimedData: def __init__(self, data, ts): self.data = data self.ts = ts class", "((data[i + 1]) << 8) if m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_", "i in range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) +", "None for item in self._q) def failure_ratio(self): total = self.total() if total ==", "1 while True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence =", "def update(self, data): now = time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0 and", "err is None: cnt += 1 sum_t += t if cnt == 0:", "duration): self._duration = duration self._q = deque() def update(self, data): now = time.time()", "payload, timeout): try: dst_addr = str(get_ip_address(addr)) except Exception as e: return timeout, f'failed", "ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload", "data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else:", "socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet =", "data_id, data_seq, payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock =", "* n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET,", "res_payload: return time_elapsed, None else: continue else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq,", "range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i +", "'>BBHHH' def chesksum(data): n = len(data) m = n % 2 sum_ =", "if err is None: cnt += 1 sum_t += t if cnt ==", "None for _, err in self._q) def failure(self): return sum(item.data[1] is not None", "2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i + 1]) << 8) if", "deque() def update(self, data): now = time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0", "self._q: t, err = item.data if err is None: cnt += 1 sum_t", "0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet", "socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header", "/ (i + 1) * 100, shorttime, longtime, sumtime)) class TimedData: def __init__(self,", "dst_addr = str(get_ip_address(addr)) except Exception as e: return timeout, f'failed to resolve domain,", "sum_ = (sum_ >> 16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ +=", "err in self._q) def failure(self): return sum(item.data[1] is not None for item in", "data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header, ip_payload = parse_ipv4_packet(data)", "icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed, None else: continue", "= time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0 and now - self._q[0].ts >", "data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0,", "sumtime += time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i", "longtime, sumtime)) class TimedData: def __init__(self, data, ts): self.data = data self.ts =", "(uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket =", ">> 16) answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >>", "socket import struct import time import uuid from collections import deque from .icmp", "(length // 16) + 1 if n == 1: return uuid.uuid4().bytes[:length] else: return", "str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence =", "arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06' header =", "return self.failure() / total def time_avg(self): cnt = 0 sum_t = 0.0 for", "n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW,", "self._q) def failure(self): return sum(item.data[1] is not None for item in self._q) def", "= time.time() - t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header,", "_FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n = len(data) m = n % 2", "def failure(self): return sum(item.data[1] is not None for item in self._q) def failure_ratio(self):", "return timeout, f'failed to resolve domain, {e}' data_type = 8 data_code = 0", "n == 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def ping(addr: str,", "def success(self): # return sum(err is None for _, err in self._q) def", "continue else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload = len(payload) if", "data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq,", "= self.total() if total == 0: return 0.0 return self.failure() / total def", "sum_t += t if cnt == 0: return 0.0 return sum_t / cnt", "self._duration = duration self._q = deque() def update(self, data): now = time.time() self._q.append(TimedData(data,", "in self._q) def failure(self): return sum(item.data[1] is not None for item in self._q)", "1]) << 8) if m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_", "def __init__(self, duration): self._duration = duration self._q = deque() def update(self, data): now", "to resolve domain, {e}' data_type = 8 data_code = 0 data_id = 0", "= header + b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast(): sock", "rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol ==", "now = time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0 and now - self._q[0].ts", "socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header +", "+ f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum =", "import socket import struct import time import uuid from collections import deque from", "domain, {e}' data_type = 8 data_code = 0 data_id = 0 icmp_packet =", ".icmp import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data):", "data_code, 0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code,", "== 0: return 0.0 return self.failure() / total def time_avg(self): cnt = 0", "t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed = time.time() - t0", "rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed = time.time() - t0 if time_elapsed >=", "data_code, icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt,", "time): sumtime += time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\"", "- t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload =", "get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n = len(data) m = n", "timeout): try: dst_addr = str(get_ip_address(addr)) except Exception as e: return timeout, f'failed to", "header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed,", "== 0: return 0.0 return sum_t / cnt def _get_random_payload(length): if length ==", "err = item.data if err is None: cnt += 1 sum_t += t", "16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer", "sumtime)) class TimedData: def __init__(self, data, ts): self.data = data self.ts = ts", "now)) while len(self._q) > 0 and now - self._q[0].ts > self._duration: self._q.popleft() class", "(data_sequence + 1) % 0xffff stat.update((time_elapsed, err)) total = stat.total() fail = stat.failure()", "n = (length // 16) + 1 if n == 1: return uuid.uuid4().bytes[:length]", "data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id,", "select.select([rawsocket], [], [], timeout - time_elapsed) if len(rlist) == 0: return timeout, 'timeout'", "print(msg.format(i + 1, accept, i + 1 - accept, (i + 1 -", "= 0.0 for item in self._q: t, err = item.data if err is", "(sum_ >> 16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >>", "= 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet,", "payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,", "struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt,", "8 | (answer << 8 & 0xff00) return answer def dealtime(dst_addr, sumtime, shorttime,", "total = self.total() if total == 0: return 0.0 return self.failure() / total", "== 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i + 1", "payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed = time.time() -", "return answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time): sumtime += time", "== 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0,", "time_elapsed, None else: continue else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload", "# 将高于16位与低16位相加 sum_ = (sum_ >> 16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加", "(sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer = ~sum_", "if header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload == res_payload: return", "dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time): sumtime += time print(sumtime) if i", "icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet", "parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n = len(data) m = n %", "_get_random_payload(length): if length == 0: return b'' n = (length // 16) +", "MovingStatistic: def __init__(self, duration): self._duration = duration self._q = deque() def update(self, data):", "print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type =", "* 100, shorttime, longtime, sumtime)) class TimedData: def __init__(self, data, ts): self.data =", "return time_elapsed, None else: continue else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload):", "b'\\x08\\x00') packet = header + b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close() def", "err)) total = stat.total() fail = stat.failure() print('total:', total, ', failed:', fail, ',", "icmp_chesksum, data_id, data_seq, payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock", "= select.select([rawsocket], [], [], timeout - time_elapsed) if len(rlist) == 0: return timeout,", "socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06' header = struct.pack('>6s6s2s', b'\\xff\\xff\\xff\\xff\\xff\\xff', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', ether_type)", "data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq)", "0xffff stat.update((time_elapsed, err)) total = stat.total() fail = stat.failure() print('total:', total, ', failed:',", "None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa',", "<< 8 & 0xff00) return answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i,", "i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i +", "time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0 and now - self._q[0].ts > self._duration:", "socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64),", "data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET))", "is not None for item in self._q) def failure_ratio(self): total = self.total() if", "e: return timeout, f'failed to resolve domain, {e}' data_type = 8 data_code =", "0: return 0.0 return self.failure() / total def time_avg(self): cnt = 0 sum_t", "sumtime, shorttime, longtime, accept, i, time): sumtime += time print(sumtime) if i ==", "m = n % 2 sum_ = 0 for i in range(0, n", "time_avg(self): cnt = 0 sum_t = 0.0 for item in self._q: t, err", "cnt += 1 sum_t += t if cnt == 0: return 0.0 return", "// 16) + 1 if n == 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes", "+= 1 sum_t += t if cnt == 0: return 0.0 return sum_t", "= (length // 16) + 1 if n == 1: return uuid.uuid4().bytes[:length] else:", "len(payload) if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq)", "= 0 data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0", "n % 2 sum_ = 0 for i in range(0, n - m,", "if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i", "(i + 1) * 100, shorttime, longtime, sumtime)) class TimedData: def __init__(self, data,", "_ = select.select([rawsocket], [], [], timeout - time_elapsed) if len(rlist) == 0: return", "data_type = 8 data_code = 0 data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code,", "total == 0: return 0.0 return self.failure() / total def time_avg(self): cnt =", "cnt = 0 sum_t = 0.0 for item in self._q: t, err =", "as e: return timeout, f'failed to resolve domain, {e}' data_type = 8 data_code", "import deque from .icmp import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET =", "- self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q) # def", "print('total:', total, ', failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr,", "= ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 | (answer", "return sum(item.data[1] is not None for item in self._q) def failure_ratio(self): total =", "rlist, _, _ = select.select([rawsocket], [], [], timeout - time_elapsed) if len(rlist) ==", "print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i + 1 - accept,", "1 - accept, (i + 1 - accept) / (i + 1) *", "def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time): sumtime += time print(sumtime) if", "- accept) / (i + 1) * 100, shorttime, longtime, sumtime)) class TimedData:", "build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True:", "(data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >> 16) + (sum_ & 0xffff) #", "= struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s'", "= 1 while True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence", "= parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed, None else: continue else: continue", "8 & 0xff00) return answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time):", "success(self): # return sum(err is None for _, err in self._q) def failure(self):", "8 data_code = 0 data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence,", "self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q) # def success(self): # return", "= stat.total() fail = stat.failure() print('total:', total, ', failed:', fail, ', average time:',", "stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr)) except", "= time.time() - t0 if time_elapsed >= timeout: return timeout, 'timeout' rlist, _,", "# 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer = ~sum_ & 0xffff #", "return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))", "1 if n == 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def", "timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header, ip_payload", "+= time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i +", ">= timeout: return timeout, 'timeout' rlist, _, _ = select.select([rawsocket], [], [], timeout", "import time import uuid from collections import deque from .icmp import parse_icmp_packet from", "| (answer << 8 & 0xff00) return answer def dealtime(dst_addr, sumtime, shorttime, longtime,", "for _, err in self._q) def failure(self): return sum(item.data[1] is not None for", "= str(get_ip_address(addr)) except Exception as e: return timeout, f'failed to resolve domain, {e}'", "len(data) m = n % 2 sum_ = 0 for i in range(0,", "== res_payload: return time_elapsed, None else: continue else: continue def build_icmp_packet(data_type, data_code, data_id,", "self.failure() / total def time_avg(self): cnt = 0 sum_t = 0.0 for item", "<< 8) if m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >>", "= PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed,", "= chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt =", "+= (data[i]) + ((data[i + 1]) << 8) if m: sum_ += (data[-1])", "# print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header =", "__init__(self, data, ts): self.data = data self.ts = ts class MovingStatistic: def __init__(self,", "timeout: return timeout, 'timeout' rlist, _, _ = select.select([rawsocket], [], [], timeout -", "payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload)", "payload): l_payload = len(payload) if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code,", "def failure_ratio(self): total = self.total() if total == 0: return 0.0 return self.failure()", "data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet =", "TimedData: def __init__(self, data, ts): self.data = data self.ts = ts class MovingStatistic:", "+ b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET,", "& 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 | (answer << 8", "return b'' n = (length // 16) + 1 if n == 1:", "ts class MovingStatistic: def __init__(self, duration): self._duration = duration self._q = deque() def", "return 0.0 return sum_t / cnt def _get_random_payload(length): if length == 0: return", "def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06' header", "PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed, err", "while True: time_elapsed = time.time() - t0 if time_elapsed >= timeout: return timeout,", "len(self._q) > 0 and now - self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def", "= n % 2 sum_ = 0 for i in range(0, n -", "(answer << 8 & 0xff00) return answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept,", "l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum =", "is None for _, err in self._q) def failure(self): return sum(item.data[1] is not", "return sum_t / cnt def _get_random_payload(length): if length == 0: return b'' n", "if len(rlist) == 0: return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed =", "uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat =", "print(packet) # print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800)))", "+= t if cnt == 0: return 0.0 return sum_t / cnt def", "= 0 sum_t = 0.0 for item in self._q: t, err = item.data", "# print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type", "= struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET,", "100, shorttime, longtime, sumtime)) class TimedData: def __init__(self, data, ts): self.data = data", "= answer >> 8 | (answer << 8 & 0xff00) return answer def", "sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06'", "stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True:", "select import socket import struct import time import uuid from collections import deque", "(sum_ >> 16) answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer", "stat.total() fail = stat.failure() print('total:', total, ', failed:', fail, ', average time:', stat.time_avg())", "i + 1 - accept, (i + 1 - accept) / (i +", "update(self, data): now = time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0 and now", "sum(err is None for _, err in self._q) def failure(self): return sum(item.data[1] is", "is None: cnt += 1 sum_t += t if cnt == 0: return", "if cnt == 0: return 0.0 return sum_t / cnt def _get_random_payload(length): if", "continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload = len(payload) if l_payload ==", "len(self._q) # def success(self): # return sum(err is None for _, err in", "class MovingStatistic: def __init__(self, duration): self._duration = duration self._q = deque() def update(self,", "chesksum(data): n = len(data) m = n % 2 sum_ = 0 for", "= rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol", "传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i + 1]) << 8) if m: sum_", "0 data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 =", "+ 1 - accept, (i + 1 - accept) / (i + 1)", "m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >> 16) + (sum_", "1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0, timeout=3.0):", "data_code, data_id, data_seq, payload): l_payload = len(payload) if l_payload == 0: icmp_packet =", "item in self._q: t, err = item.data if err is None: cnt +=", "self.ts = ts class MovingStatistic: def __init__(self, duration): self._duration = duration self._q =", "sum_ = 0 for i in range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位", "answer = answer >> 8 | (answer << 8 & 0xff00) return answer", "sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00')", "_ = rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header, ip_payload = parse_ipv4_packet(data) if", "payload == res_payload: return time_elapsed, None else: continue else: continue def build_icmp_packet(data_type, data_code,", "= len(data) m = n % 2 sum_ = 0 for i in", "b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello, world!' sock.send(packet) print(packet) # print(res)", "failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout):", "data_code, data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed", "and now - self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q)", "def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800)))", "if m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >> 16) +", "% 0xffff stat.update((time_elapsed, err)) total = stat.total() fail = stat.failure() print('total:', total, ',", "0.0 for item in self._q: t, err = item.data if err is None:", "failure(self): return sum(item.data[1] is not None for item in self._q) def failure_ratio(self): total", "resolve domain, {e}' data_type = 8 data_code = 0 data_id = 0 icmp_packet", "16) + 1 if n == 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes *", "data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum,", "sum(item.data[1] is not None for item in self._q) def failure_ratio(self): total = self.total()", "time_elapsed >= timeout: return timeout, 'timeout' rlist, _, _ = select.select([rawsocket], [], [],", "m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i + 1]) << 8)", "t, err = item.data if err is None: cnt += 1 sum_t +=", "print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s',", "0: return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time() - t0", "duration self._q = deque() def update(self, data): now = time.time() self._q.append(TimedData(data, now)) while", "+ 1) * 100, shorttime, longtime, sumtime)) class TimedData: def __init__(self, data, ts):", "self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q) # def success(self):", "data_sequence = (data_sequence + 1) % 0xffff stat.update((time_elapsed, err)) total = stat.total() fail", "data_seq, payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET,", "stat.update((time_elapsed, err)) total = stat.total() fail = stat.failure() print('total:', total, ', failed:', fail,", "+ 1) % 0xffff stat.update((time_elapsed, err)) total = stat.total() fail = stat.failure() print('total:',", "= struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello, world!' sock.send(packet) print(packet)", "\"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i + 1 - accept, (i + 1", "header + b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast(): sock =", "= ts class MovingStatistic: def __init__(self, duration): self._duration = duration self._q = deque()", "data_code = 0 data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload)", "= stat.failure() print('total:', total, ', failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval) def", "t if cnt == 0: return 0.0 return sum_t / cnt def _get_random_payload(length):", "socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06' header = struct.pack('>6s6s2s', b'\\xff\\xff\\xff\\xff\\xff\\xff', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb',", "= parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload ==", "+ 1, accept, i + 1 - accept, (i + 1 - accept)", "0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id,", "data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 = time.time()", "[], [], timeout - time_elapsed) if len(rlist) == 0: return timeout, 'timeout' data,", "> self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q) # def success(self): #", "world!' sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))", "self.data = data self.ts = ts class MovingStatistic: def __init__(self, duration): self._duration =", "8) if m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >> 16)", "struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet", ">> 16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16)", "time.time() - t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload", "icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET +", "= 0 for i in range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_", "1) * 100, shorttime, longtime, sumtime)) class TimedData: def __init__(self, data, ts): self.data", "in self._q: t, err = item.data if err is None: cnt += 1", "'timeout' rlist, _, _ = select.select([rawsocket], [], [], timeout - time_elapsed) if len(rlist)", "total def time_avg(self): cnt = 0 sum_t = 0.0 for item in self._q:", "= (sum_ >> 16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_", "% 2 sum_ = 0 for i in range(0, n - m, 2):", "while len(self._q) > 0 and now - self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic):", "stat.failure() print('total:', total, ', failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket,", "total(self): return len(self._q) # def success(self): # return sum(err is None for _,", "str(get_ip_address(addr)) except Exception as e: return timeout, f'failed to resolve domain, {e}' data_type", "sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0',", "0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 | (answer << 8 &", "try: dst_addr = str(get_ip_address(addr)) except Exception as e: return timeout, f'failed to resolve", "0.0 return sum_t / cnt def _get_random_payload(length): if length == 0: return b''", "header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello, world!' sock.send(packet)", "0 icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr,", "= 8 data_code = 0 data_id = 0 icmp_packet = build_icmp_packet(data_type, data_code, data_id,", "if length == 0: return b'' n = (length // 16) + 1", "deque from .icmp import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH'", "timeout - time_elapsed) if len(rlist) == 0: return timeout, 'timeout' data, _ =", "def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload = len(payload) if l_payload == 0:", "i, time): sumtime += time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg =", "def time_avg(self): cnt = 0 sum_t = 0.0 for item in self._q: t,", "== 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet)", "# 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i + 1]) << 8) if m:", "for i in range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i])", "ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence", "- accept, (i + 1 - accept) / (i + 1) * 100,", "answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 |", "collections import deque from .icmp import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET", "def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr)) except Exception as", "', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr", "= data self.ts = ts class MovingStatistic: def __init__(self, duration): self._duration = duration", "import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n", "else: return (uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0)", "class PingStat(MovingStatistic): def total(self): return len(self._q) # def success(self): # return sum(err is", "return (uuid.uuid4().bytes * n)[:length] def ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket", "= deque() def update(self, data): now = time.time() self._q.append(TimedData(data, now)) while len(self._q) >", "if n == 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length] def ping(addr:", "average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr =", "return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time() - t0 header,", "data_id, data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code,", "data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed =", "l_payload = len(payload) if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0,", "= socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet", "sum_t = 0.0 for item in self._q: t, err = item.data if err", "data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None,", "data_seq, payload): l_payload = len(payload) if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type,", "socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello, world!'", "= len(payload) if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id,", "fail = stat.failure() print('total:', total, ', failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval)", "~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 | (answer <<", "import uuid from collections import deque from .icmp import parse_icmp_packet from .ip import", "uuid from collections import deque from .icmp import parse_icmp_packet from .ip import get_ip_address,", "_get_random_payload(64), timeout) data_sequence = (data_sequence + 1) % 0xffff stat.update((time_elapsed, err)) total =", "== 0: return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time() -", "_, err in self._q) def failure(self): return sum(item.data[1] is not None for item", "= \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i + 1 - accept, (i +", "import struct import time import uuid from collections import deque from .icmp import", "data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed = time.time()", "+ 1]) << 8) if m: sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ =", "t0 if time_elapsed >= timeout: return timeout, 'timeout' rlist, _, _ = select.select([rawsocket],", "+= (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >> 16) + (sum_ & 0xffff)", "将高于16位与低16位相加 sum_ = (sum_ >> 16) + (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_", "total, ', failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence,", "from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n = len(data)", "def total(self): return len(self._q) # def success(self): # return sum(err is None for", "in range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i", "for item in self._q: t, err = item.data if err is None: cnt", "icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type,", "data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence + 1) % 0xffff stat.update((time_elapsed, err)) total", "(dst_addr, 0)) while True: time_elapsed = time.time() - t0 if time_elapsed >= timeout:", "msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i + 1 - accept, (i", "return sum(err is None for _, err in self._q) def failure(self): return sum(item.data[1]", "_ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence + 1) % 0xffff stat.update((time_elapsed,", "1 - accept) / (i + 1) * 100, shorttime, longtime, sumtime)) class", "data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type,", "0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer = ~sum_ & 0xffff", "icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet def play_packet():", "+ 1 if n == 1: return uuid.uuid4().bytes[:length] else: return (uuid.uuid4().bytes * n)[:length]", "answer >> 8 | (answer << 8 & 0xff00) return answer def dealtime(dst_addr,", "time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1,", "print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept,", "time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr))", "chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt = _FMT_ICMP_PACKET", "+= (sum_ >> 16) answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer =", "for item in self._q) def failure_ratio(self): total = self.total() if total == 0:", "return len(self._q) # def success(self): # return sum(err is None for _, err", "if time_elapsed >= timeout: return timeout, 'timeout' rlist, _, _ = select.select([rawsocket], [],", "return 0.0 return self.failure() / total def time_avg(self): cnt = 0 sum_t =", "parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n =", "answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time): sumtime += time print(sumtime)", "sum_ += (data[i]) + ((data[i + 1]) << 8) if m: sum_ +=", "主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8 | (answer << 8 & 0xff00) return", "# return sum(err is None for _, err in self._q) def failure(self): return", "timeout) data_sequence = (data_sequence + 1) % 0xffff stat.update((time_elapsed, err)) total = stat.total()", "self.total() if total == 0: return 0.0 return self.failure() / total def time_avg(self):", "return timeout, 'timeout' rlist, _, _ = select.select([rawsocket], [], [], timeout - time_elapsed)", "0: return b'' n = (length // 16) + 1 if n ==", "fail, ', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try:", "16) answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer = answer >> 8", "parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload == res_payload:", "build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload = len(payload) if l_payload == 0: icmp_packet", "struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(),", "& 0xff00) return answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time): sumtime", "err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence + 1) %", "struct import time import uuid from collections import deque from .icmp import parse_icmp_packet", "socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed, err = _ping_once(rawsocket, addr,", ".ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n = len(data) m", "True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence +", "time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr)) except Exception", "ts): self.data = data self.ts = ts class MovingStatistic: def __init__(self, duration): self._duration", "sum_t / cnt def _get_random_payload(length): if length == 0: return b'' n =", "/ total def time_avg(self): cnt = 0 sum_t = 0.0 for item in", "- time_elapsed) if len(rlist) == 0: return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500)", "True: time_elapsed = time.time() - t0 if time_elapsed >= timeout: return timeout, 'timeout'", "total = stat.total() fail = stat.failure() print('total:', total, ', failed:', fail, ', average", "_FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum", "cnt def _get_random_payload(length): if length == 0: return b'' n = (length //", "', failed:', fail, ', average time:', stat.time_avg()) time.sleep(interval) def _ping_once(rawsocket, addr, data_sequence, payload,", "time import uuid from collections import deque from .icmp import parse_icmp_packet from .ip", "import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def chesksum(data): n = len(data) m =", "cnt == 0: return 0.0 return sum_t / cnt def _get_random_payload(length): if length", "timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while", "/ cnt def _get_random_payload(length): if length == 0: return b'' n = (length", "icmp_packet = build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0))", "sum_ += (sum_ >> 16) answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序) answer", "icmp_packet def play_packet(): # print(socket.getaddrinfo(socket.gethostname(), None, family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0',", "4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg = \"数据包:已发送={0},接收={1},丢失={2}({3}%丢失),\\n往返行程的估计时间(以毫秒为单位):\\n\\t最短={4}ms,最长={5}ms,平均={6}ms\" print(msg.format(i + 1, accept, i + 1 -", "- m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i + 1]) <<", "0)) while True: time_elapsed = time.time() - t0 if time_elapsed >= timeout: return", "longtime, accept, i, time): sumtime += time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr))", "# def success(self): # return sum(err is None for _, err in self._q)", "f'failed to resolve domain, {e}' data_type = 8 data_code = 0 data_id =", "self._q) def failure_ratio(self): total = self.total() if total == 0: return 0.0 return", "= chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet", "data, ts): self.data = data self.ts = ts class MovingStatistic: def __init__(self, duration):", "f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet)", "= struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload) icmp_chesksum = chesksum(icmp_packet) icmp_packet =", "family=socket.AddressFamily.AF_INET)) sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb',", "(data[i]) + ((data[i + 1]) << 8) if m: sum_ += (data[-1]) #", "= (data_sequence + 1) % 0xffff stat.update((time_elapsed, err)) total = stat.total() fail =", "struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type,", "time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence + 1)", "1 sum_t += t if cnt == 0: return 0.0 return sum_t /", "else: continue else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload = len(payload)", "packet = header + b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast():", "b'' n = (length // 16) + 1 if n == 1: return", ">> 8 | (answer << 8 & 0xff00) return answer def dealtime(dst_addr, sumtime,", "= build_icmp_packet(data_type, data_code, data_id, data_sequence, payload) t0 = time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while", "1, accept, i + 1 - accept, (i + 1 - accept) /", "0xff00) return answer def dealtime(dst_addr, sumtime, shorttime, longtime, accept, i, time): sumtime +=", "b'hello, world!' sock.send(packet) print(packet) # print(res) sock.close() def arp_boardcast(): sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,", "data_sequence = 1 while True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout)", "__init__(self, duration): self._duration = duration self._q = deque() def update(self, data): now =", "addr, data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr)) except Exception as e: return", "{e}' data_type = 8 data_code = 0 data_id = 0 icmp_packet = build_icmp_packet(data_type,", "import select import socket import struct import time import uuid from collections import", "timeout, f'failed to resolve domain, {e}' data_type = 8 data_code = 0 data_id", "failure_ratio(self): total = self.total() if total == 0: return 0.0 return self.failure() /", "data_id, data_seq, payload): l_payload = len(payload) if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET,", "time_elapsed = time.time() - t0 header, ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp':", "time_elapsed) if len(rlist) == 0: return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed", "data_type, data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code,", "icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum = chesksum(icmp_packet) icmp_packet =", "- t0 if time_elapsed >= timeout: return timeout, 'timeout' rlist, _, _ =", "parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed, None else: continue else: continue def", "sum_ += (data[-1]) # 将高于16位与低16位相加 sum_ = (sum_ >> 16) + (sum_ &", "0.0 return self.failure() / total def time_avg(self): cnt = 0 sum_t = 0.0", "= _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id, data_seq, payload)", "2 sum_ = 0 for i in range(0, n - m, 2): #", "accept) / (i + 1) * 100, shorttime, longtime, sumtime)) class TimedData: def", "header, ip_payload = parse_ipv4_packet(data) if header.protocol == 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if", "shorttime, longtime, sumtime)) class TimedData: def __init__(self, data, ts): self.data = data self.ts", "def ping(addr: str, interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)", "n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ += (data[i]) + ((data[i + 1])", "sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06' header = struct.pack('>6s6s2s',", "None else: continue else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload =", "'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed, None else:", "from .icmp import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet _FMT_ICMP_PACKET = '>BBHHH' def", "res_payload = parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed, None else: continue else:", "= item.data if err is None: cnt += 1 sum_t += t if", "while True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence", "_, _ = select.select([rawsocket], [], [], timeout - time_elapsed) if len(rlist) == 0:", "if payload == res_payload: return time_elapsed, None else: continue else: continue def build_icmp_packet(data_type,", "None: cnt += 1 sum_t += t if cnt == 0: return 0.0", "time_elapsed = time.time() - t0 if time_elapsed >= timeout: return timeout, 'timeout' rlist,", "= '>BBHHH' def chesksum(data): n = len(data) m = n % 2 sum_", "time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed = time.time() - t0 if time_elapsed", "interval=3.0, timeout=3.0): stat = PingStat(60.0) rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1", "self._q = deque() def update(self, data): now = time.time() self._q.append(TimedData(data, now)) while len(self._q)", "item in self._q) def failure_ratio(self): total = self.total() if total == 0: return", "from collections import deque from .icmp import parse_icmp_packet from .ip import get_ip_address, parse_ipv4_packet", "0: return 0.0 return sum_t / cnt def _get_random_payload(length): if length == 0:", "socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed, err = _ping_once(rawsocket, addr, data_sequence,", "else: continue def build_icmp_packet(data_type, data_code, data_id, data_seq, payload): l_payload = len(payload) if l_payload", "> 0 and now - self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self):", "data): now = time.time() self._q.append(TimedData(data, now)) while len(self._q) > 0 and now -", "Exception as e: return timeout, f'failed to resolve domain, {e}' data_type = 8", "sock.bind(('wlp3s0', socket.htons(0x0800))) header = struct.pack('>6s6s2s', b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa', b'\\xbb\\xbb\\xbb\\xbb\\xbb\\xbb', b'\\x08\\x00') packet = header + b'hello,", "accept, i, time): sumtime += time print(sumtime) if i == 4: print(\"{0}的Ping统计信息:\".format(dst_addr)) msg", "+ (sum_ & 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer =", "def _get_random_payload(length): if length == 0: return b'' n = (length // 16)", "shorttime, longtime, accept, i, time): sumtime += time print(sumtime) if i == 4:", "& 0xffff) # 如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer = ~sum_ &", "len(rlist) == 0: return timeout, 'timeout' data, _ = rawsocket.recvfrom(1500) time_elapsed = time.time()", "如果还有高于16位,将继续与低16位相加 sum_ += (sum_ >> 16) answer = ~sum_ & 0xffff # 主机字节序转网络字节序列(参考小端序转大端序)", "0 and now - self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return", "if total == 0: return 0.0 return self.failure() / total def time_avg(self): cnt", "_ping_once(rawsocket, addr, data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr)) except Exception as e:", "icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, icmp_chesksum, data_id, data_seq) else: fmt", "icmp_chesksum = chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return", "accept, (i + 1 - accept) / (i + 1) * 100, shorttime,", "in self._q) def failure_ratio(self): total = self.total() if total == 0: return 0.0", "== 0: return b'' n = (length // 16) + 1 if n", "fmt = _FMT_ICMP_PACKET + f'{l_payload}s' icmp_packet = struct.pack(fmt, data_type, data_code, 0, data_id, data_seq,", "= struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet def play_packet(): #", "0 sum_t = 0.0 for item in self._q: t, err = item.data if", "data self.ts = ts class MovingStatistic: def __init__(self, duration): self._duration = duration self._q", "item.data if err is None: cnt += 1 sum_t += t if cnt", "rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) data_sequence = 1 while True: time_elapsed, err =", "timeout, 'timeout' rlist, _, _ = select.select([rawsocket], [], [], timeout - time_elapsed) if", "+ ((data[i + 1]) << 8) if m: sum_ += (data[-1]) # 将高于16位与低16位相加", "0 for i in range(0, n - m, 2): # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 sum_ +=", "= socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) sock.bind(('wlp3s0', socket.htons(0x0800))) ether_type = b'\\x08\\x06' header = struct.pack('>6s6s2s', b'\\xff\\xff\\xff\\xff\\xff\\xff',", "now - self._q[0].ts > self._duration: self._q.popleft() class PingStat(MovingStatistic): def total(self): return len(self._q) #", "= time.time() rawsocket.sendto(icmp_packet, (dst_addr, 0)) while True: time_elapsed = time.time() - t0 if", "if l_payload == 0: icmp_packet = struct.pack(_FMT_ICMP_PACKET, data_type, data_code, 0, data_id, data_seq) icmp_chesksum", "== 'icmp': icmp_header, res_payload = parse_icmp_packet(ip_payload) if payload == res_payload: return time_elapsed, None", "chesksum(icmp_packet) icmp_packet = struct.pack(fmt, data_type, data_code, icmp_chesksum, data_id, data_seq, payload) return icmp_packet def", "+ 1 - accept) / (i + 1) * 100, shorttime, longtime, sumtime))", "data_sequence, payload, timeout): try: dst_addr = str(get_ip_address(addr)) except Exception as e: return timeout,", "= _ping_once(rawsocket, addr, data_sequence, _get_random_payload(64), timeout) data_sequence = (data_sequence + 1) % 0xffff" ]
[ "f.readlines(): match = require_pattern.search(line) if match: calee = match.group(1) calee_node = calee.replace(\".\", \"__\")", "print(\"digraph require_graph {\") for path in glob(\"**/*.lua\", recursive=True): with open(path) as f: caller", "in f.readlines(): match = require_pattern.search(line) if match: calee = match.group(1) calee_node = calee.replace(\".\",", "\"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match = require_pattern.search(line) if match:", "for line in f.readlines(): match = require_pattern.search(line) if match: calee = match.group(1) calee_node", "glob import glob import re require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path", "re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in glob(\"**/*.lua\", recursive=True): with open(path) as f:", "= path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line", "require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in glob(\"**/*.lua\", recursive=True): with open(path)", "caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match =", "from glob import glob import re require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for", "if match: calee = match.group(1) calee_node = calee.replace(\".\", \"__\") print(f\" {caller_node} -> {calee_node};\")", "recursive=True): with open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\",", "\".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match", "print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match = require_pattern.search(line) if match: calee", "[label=\\\"{caller}\\\"];\") for line in f.readlines(): match = require_pattern.search(line) if match: calee = match.group(1)", "import re require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in glob(\"**/*.lua\", recursive=True):", "caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for", "path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in", "import glob import re require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in", "with open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\")", "= require_pattern.search(line) if match: calee = match.group(1) calee_node = calee.replace(\".\", \"__\") print(f\" {caller_node}", "f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\")", "match = require_pattern.search(line) if match: calee = match.group(1) calee_node = calee.replace(\".\", \"__\") print(f\"", "open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\"", "line in f.readlines(): match = require_pattern.search(line) if match: calee = match.group(1) calee_node =", "caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match = require_pattern.search(line) if", "match: calee = match.group(1) calee_node = calee.replace(\".\", \"__\") print(f\" {caller_node} -> {calee_node};\") print(\"}\")", "= re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in glob(\"**/*.lua\", recursive=True): with open(path) as", "in glob(\"**/*.lua\", recursive=True): with open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node", "{\") for path in glob(\"**/*.lua\", recursive=True): with open(path) as f: caller = path.replace(\".lua\",", "for path in glob(\"**/*.lua\", recursive=True): with open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\",", "glob import re require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in glob(\"**/*.lua\",", "\"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines():", "= caller.replace(\".\", \"__\") print(f\" {caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match = require_pattern.search(line)", "re require_pattern = re.compile(r'\\brequire\\(\"(.*)\"\\)') print(\"digraph require_graph {\") for path in glob(\"**/*.lua\", recursive=True): with", "path in glob(\"**/*.lua\", recursive=True): with open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\")", "glob(\"**/*.lua\", recursive=True): with open(path) as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node =", "require_pattern.search(line) if match: calee = match.group(1) calee_node = calee.replace(\".\", \"__\") print(f\" {caller_node} ->", "as f: caller = path.replace(\".lua\", \"\").replace(\"/\", \".\") caller_node = caller.replace(\".\", \"__\") print(f\" {caller_node}", "require_graph {\") for path in glob(\"**/*.lua\", recursive=True): with open(path) as f: caller =", "{caller_node} [label=\\\"{caller}\\\"];\") for line in f.readlines(): match = require_pattern.search(line) if match: calee =" ]
[ "## ## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels)", "Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an xarray data array", "different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active cells in", "conductance. # condleft = hk1[0,0,0] * (stageleft - zbot) * delc # condright", "methods that we will use here: * get_times() will return a list of", "The thickness of the seabed deposits was #assumed to be half the thickness", "np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to 10 - use data? calculate? vka1", "# far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for", "lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1,", "ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell centers qx_avg =", "print('Levels: ', levels) print('Extent: ', extent) # Make the plots #Print statistics print('Head", "return a list of times contained in the binary head file * get_data()", "ax = fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head", "when cheq_griddev is implemented delr = cell_spacing delc = cell_spacing delv = (dem_trans", "class to plot boundary conditions (IBOUND), plot the grid, plot head contours, and", "spacing in meters # Define inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs", "stress_period_data=spd, compact=True) #%% # Add PCG package to the MODFLOW model pcg =", "and last columns to −1. The numpy package (and Python, in general) uses", "implemented delr = cell_spacing delc = cell_spacing delv = (dem_trans - zbot) /", "from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] =", "in the matrix is the amount # of elapsed time since the previous", "= bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows", "as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color gradient genu.quick_plot(dem_trans) #", "periods in the simulation nstp_default = dt/0.5 # stress period time step divided", "Create the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc,", "flow front face already extracted ##%% ##Create the plot #f = plt.figure() #plt.subplot(1,", "a large grid. The commented section below uses the modelmap class from Tutorial", "fff[1:nlay, :, :]) qy_avg[0, :, :] = 0.5 * fff[0, :, :] #", "the plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:,", "= (ztop - zbot) / nlay #botm = np.linspace(ztop, zbot, nlay + 1)", "- zbot) * delc # condright = hk1[0,0,0] * (stageright - zbot) *", "to have fewer rows and columns #cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf,", "has a binary utility that can be used to read the heads. The", "are defined with the Basic package (BAS), which is required for every MOD-FLOW", "shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0])", "#modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm", "and column 1, and row 1 and column 201, can be referenced as", "condition #Darcy's law states that #Q = -KA(h1 - h0)/(X1 - X0) #Where", "# for ir in range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il,", "# Make the plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1,", "Masterson) nlay = 1 # 1 layer model nrow, ncol = cc[0].shape #", "dem in same projection as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] =", "# plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19", "work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level", "we can read heads from the MODFLOW binary output file, using the flopy.utils.binaryfile", "data is stored in a dictionary with key values equal to the zero-based", "the flopy.utils.binaryfile module. Included with the HeadFile object are several methods that we", "containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu", "For a GHB the values can be a two-dimensional nested list of [layer,", "here: * get_times() will return a list of times contained in the binary", "1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ##", "1 # 1 layer model nrow, ncol = cc[0].shape # to use when", "face and flow front face already extracted ##%% ##Create the plot #f =", "heads. The following statements will read the binary head file and create a", "conductance) bound_sp1 = [] stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%%", "genu from cgw.utils import feature_utils as shpu from cgw.utils import raster_utils as rastu", "y, x, z = dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip = 3", "import feature_utils as shpu from cgw.utils import raster_utils as rastu # Assign name", "and Nauset #Marsh, it was assumed that there were thick deposits of lowpermeability", "dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an xarray data array dem_vals = dem_da.values.squeeze()", "\"\"\" The pre-canned plotting doesn't seem to be able to allow averaging to", "is stored in a dictionary with key values equal to the zero-based stress", "= shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2)", "#W is width of the model cell containing the seabed (ft); #L is", "nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady)", "as np) can be used to quickly initialize the ibound array with values", "with water at sea level genu.quick_plot(strt) # plots starting condition bas = flopy.modflow.ModflowBas(mf,", "set to 0.1 ft/d. The thickness of the seabed deposits was #assumed to", "cell Using these methods, we can create head plots and hydrographs from the", "ibound value for the first and last columns to −1. The numpy package", "print('Extent: ', extent) # Make the plots #Print statistics print('Head statistics') print(' min:", "of the study area was assumed to be 1 ft/d, #which is consistent", "be used to quickly initialize the ibound array with values of 1, and", "series array [ntimes, headval] for the specified cell Using these methods, we can", "cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The", "cgw.utils import general_utils as genu from cgw.utils import feature_utils as shpu from cgw.utils", "3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5,", "drain for modification based on Masterson, 2004) conductance = 1000. # (modify 1000", "to −1. The numpy package (and Python, in general) uses zero-based indexing and", "feature_utils as shpu from cgw.utils import raster_utils as rastu # Assign name and", "modelmap class from Tutorial 1, followed by use of the plotting from the", "#ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading DEM data for that area", "delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object when transient conditions are", "# plots heads with color gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy", "function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the", "= np.arange(1,10,1) extent = (delr/2., Lx - delr/2., Ly - delc/2., delc/2.) #", "step time length (to better interpolate tidal changes, set to 0.5 hrs) perlen", "ft/d. The thickness of the seabed deposits was #assumed to be half the", "Transient General-Head Boundary Package First, we will create the GHB object, which is", "editor, but flopy has a binary utility that can be used to read", "[] #for il in range(nlay): # # Figure out looping through hk1 array", "1000 to actual conductance) bound_sp1 = [] stress_period_data = {0: bound_sp1} ghb =", "= genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y)", "- delr/2., delc/2., Ly - delc/2.) print('Levels: ', levels) print('Extent: ', extent) #", "bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to", "plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with", "MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress period 1 # Using Mean", "steady-state model #print('Adding ', len(bound_sp1), 'GHBs for stress period 1.') # #stress_period_data =", "U.S. Geological Survey, #oral commun., 2002) and the vertical hydraulic conductivity #was set", "create the GHB object, which is of the following type: flopy.modflow.ModflowGhb. The key", "# Location of BitBucket folder containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from", "time step, hrs perlen_days = dt/24. # stress period time step, days nper", "under msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)]", "for the BAS (basic) package # Added 5/28/19 \"\"\" Active cells and the", "-50. #nlay = 1 #nrow = 10 #ncol = 10 #delr = Lx/ncol", "MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary", "MODFLOW model input files mf.write_input() #%% # Run the MODFLOW model success, buff", "for changing conductance. # condleft = hk1[0,0,0] * (stageleft - zbot) * delc", "Darcy's law can be expressed as #Q = -C(h1 - h0) #where C", "the Results Now that we have successfully built and run our MODFLOW model,", "the first) perlen[0] = 1 # set first step as steady state steady", "# in meters at closest NOAA station #%% # Example of making a", "extent=(0, Lx, 0, Ly)) y, x, z = dis.get_node_coordinates() X, Y = np.meshgrid(x,", "= plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours", "ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's law states that", "to flow (L2) #h is head (L) #X is the position at which", ":, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :, 0] = 0.5 * frf[:,", "= 1000. #Ly = 1000. #ztop = 0. #zbot = -50. #nlay =", "extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) #", "ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3,", "to be able to allow averaging to reduce nrow and ncol on the", "11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0]", "the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C = KWL/M", "time decimate_by_ncells = 1 # by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y", "level (msl), 0 is msl, -1 is under msl. strt = np.ones((nlay, nrow,", "= [out_proj,[xshift,yshift],min_angle] # make transform list # Can calculate cell centers (where heads", "closest NOAA station for stages #stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1 =", "# markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig =", "period time step divided by step time length (to better interpolate tidal changes,", "- delc/2.) print('Levels: ', levels) print('Extent: ', extent) # Make the plots #Print", "qx_avg[:, :, 0] = 0.5 * frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype)", "some pre-canned plotting capabilities can can be accessed using the ModelMap class. The", "compact=True) #%% # Add PCG package to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf)", "right face and flow front face already extracted ##%% ##Create the plot #f", "hydraulic conductivity #was set to 0.1 ft/d. The thickness of the seabed deposits", "cell containing the #boundary. # still using simple conductance land_cells = active_cells &", "the hydraulic conductivity (L/T) #A is the area perpendicular to flow (L2) #h", "vka1[:,:,:]=10. # everything set to 10. # Add LPF package to the MODFLOW", "deposits #(ft/d); #W is width of the model cell containing the seabed (ft);", "Masterson, 2004) conductance = 1000. # (modify 1000 to actual conductance) bound_sp1 =", "seabed deposits (ft). #The vertical hydraulic conductivity (K) of the seabed #deposits in", "# from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to the MODFLOW model spd", "condleft]) # bound_sp1.append([il, ir, ncol - 1, stageright, condright]) ## Only 1 stress", "model #print('Adding ', len(bound_sp1), 'GHBs for stress period 1.') # #stress_period_data = {0:", "'print budget', 'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% #", "parameters (levels already set) extent = (delr/2., Lx - delr/2., delc/2., Ly -", "commented out section using modelmap \"\"\" ## Flow right face and flow front", "modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing SEAWAT) ucnobj =", "ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object when transient conditions", "# Variables for the BAS (basic) package # Added 5/28/19 \"\"\" Active cells", "= 10 # days dt = 6 # stress period time step, hrs", "steady state nstp = [nstp_default]*nper # number of time steps in a stress", "Included with the HeadFile object are several methods that we will use here:", "= hk1[0,0,0] * (stageright - zbot) * delc # for ir in range(nrow):", "period time step, days nper = int(total_length/perlen_days) # the number of stress periods", "cell spacing in meters # Define inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing}", "fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx, 0, Ly))", "shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the outputs", ":] = 0.5 * fff[0, :, :] # Make the plot fig =", "{'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same projection as model boundary shp dem_trans", "# Average flows to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:]", "nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS object #dis", "stress periods in the simulation nstp_default = dt/0.5 # stress period time step", "[m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading DEM data for that area dem_fname", "text editor, but flopy has a binary utility that can be used to", "2 DIS object when transient conditions are implemented # dis = flopy.modflow.ModflowDis(mf, nlay,", "will return a list of times contained in the binary head file *", "shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid cell spacing in meters", "(ft2/d); #K is vertical hydraulic conductivity of seabed deposits #(ft/d); #W is width", "that Darcy's law can be expressed as #Q = -C(h1 - h0) #where", "will return a time series array [ntimes, headval] for the specified cell Using", "is recognizing that the boundary data is stored in a dictionary with key", "= 1000. #ztop = 0. #zbot = -50. #nlay = 1 #nrow =", "to compute the saturated thickness for cases of unconfined flow. ibound = np.ones((1,", "head.max()) print(' std: ', head.std()) \"\"\" Again, commented out section using modelmap \"\"\"", "and X terms so that Darcy's law can be expressed as #Q =", "saturated thickness for cases of unconfined flow. ibound = np.ones((1, 201)) ibound[0, 0]", "for the specified time * get_ts() will return a time series array [ntimes,", "#discharge areas in other areas on Cape Cod (Masterson and #others, 1998). In", "time steps in a stress period nstp[0] = 1 #Tutorial 2 default time", "= rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X)", "bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW", "2004) conductance = 1000. # (modify 1000 to actual conductance) bound_sp1 = []", "= modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to fix grid to have fewer", "making a MODFLOW-like grid from a shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp')", "which head is measured (L) #Conductance combines the K, A and X terms", "Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom of model is horizontal,", "where #C is hydraulic conductance of the seabed (ft2/d); #K is vertical hydraulic", "cgw.utils import raster_utils as rastu # Assign name and create modflow model object", "nested list of [layer, row, column, stage, conductance]: Datums for 8447435, Chatham, Lydia", "to 0.1 ft/d. The thickness of the seabed deposits was #assumed to be", "'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile)", "10. # Add LPF package to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1,", "the boundary conditions for that stress period. For a GHB the values can", "and budget file objects already created # Setup contour parameters (levels already set)", "step divided by step time length (to better interpolate tidal changes, set to", "are active (value is positive), inactive (value is 0), or fixed head (value", "genu.quick_plot(ibound) # plots boundary condition: 1 is above mean sea level (msl), 0", "genu.quick_plot(strt) # plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added", "key values equal to the zero-based stress period number and values equal to", "using single conductance value (see drain for modification based on Masterson, 2004) conductance", "from cgw.utils import feature_utils as shpu from cgw.utils import raster_utils as rastu #", "fewer rows and columns #cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head)", "with the Basic package (BAS), which is required for every MOD-FLOW model. It", ":, :]) qy_avg[0, :, :] = 0.5 * fff[0, :, :] # Make", "#plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1,", "= plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest',", "#modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to", "# make transform list # Can calculate cell centers (where heads are calculated),", "decimate_by_ncells = 1 # by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y =", "\"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds'))", "[False]*nper steady[0] = True # first step steady state nstp = [nstp_default]*nper #", "seabed #deposits in most of the study area was assumed to be 1", "= np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom of model is horizontal, approx.", "flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp,", "as [0,0], and [0,−1], respectively. Although this simulation is for steady flow, starting", "have fewer rows and columns #cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff,", "HeadFile object are several methods that we will use here: * get_times() will", "everything set to 10. # Add LPF package to the MODFLOW model lpf", "at sea level genu.quick_plot(strt) # plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt)", "np.float) vka1[:,:,:]=10. # everything set to 10. # Add LPF package to the", "start with water at sea level genu.quick_plot(strt) # plots starting condition bas =", "from the MODFLOW binary output file, using the flopy.utils.binaryfile module. Included with the", "point (need to change the first) perlen[0] = 1 # set first step", "will create the GHB object, which is of the following type: flopy.modflow.ModflowGhb. The", "implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\"", "measured (L) #Conductance combines the K, A and X terms so that Darcy's", "we can create head plots and hydrographs from the model results.: \"\"\" #", "active_dem_heights # start with freshwater at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level #", "hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10,", "this simulation is for steady flow, starting heads still need to be specified.", "bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value (see drain for", "rastu.load_geotif(dem_fname) # da is an xarray data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y,", "= mean_sea_level #stageright = mean_sea_level #bound_sp1 = [] #for il in range(nlay): #", "stress period time step, days nper = int(total_length/perlen_days) # the number of stress", "out all of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform =", "values of 1, and then set the ibound value for the first and", "#stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value", "step, days nper = int(total_length/perlen_days) # the number of stress periods in the", "nper = int(total_length/perlen_days) # the number of stress periods in the simulation nstp_default", "#qm = modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs", ":, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1,", "is positive), inactive (value is 0), or fixed head (value is negative). The", "period 1 # Using Mean Sea Level (MSL) in meters at closest NOAA", "Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom of", "the Basic package (BAS), which is required for every MOD-FLOW model. It contains", "columns #cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" #", "## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs,", "3/8/19 - creates matrix where hydraulic conductivities (hk = horiz, vk = vert)", "\"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds')", "X0) #Where Q is the flow (L3/T) #K is the hydraulic conductivity (L/T)", "# in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading", "#nrow = 10 #ncol = 10 #delr = Lx/ncol #delc = Ly/nrow #delv", "was #assumed to be half the thickness of the model cell containing the", "a binary data output file. We cannot look at these heads with a", "-KA(h1 - h0)/(X1 - X0) #Where Q is the flow (L3/T) #K is", "#Lx = 1000. #Ly = 1000. #ztop = 0. #zbot = -50. #nlay", "in the binary head file * get_data() will return a three-dimensional head array", "# # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ## lc =", "(where ibound is negative), and as a starting point to compute the saturated", "= modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black',", "steady=steady) #%% # Variables for the BAS (basic) package # Added 5/28/19 \"\"\"", "and flow front face already extracted ##%% ##Create the plot #f = plt.figure()", ":] = 0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay, :, :]) qy_avg[0, :,", "same projection as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans)", "use the modelmap class to plot boundary conditions (IBOUND), plot the grid, plot", "of time steps in a stress period nstp[0] = 1 #Tutorial 2 default", "oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG package to the MODFLOW", "rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to the MODFLOW model", "step as steady state steady = [False]*nper steady[0] = True # first step", "= [True, False, False] #%% # Create the discretization (DIS) object dis =", ":, :] + fff[1:nlay, :, :]) qy_avg[0, :, :] = 0.5 * fff[0,", "+ 1) #%% \"\"\" Time Stepping \"\"\" # Time step parameters total_length =", "in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add", "zbot) / nlay #botm = np.linspace(ztop, zbot, nlay + 1) #%% \"\"\" Time", "of unconfined flow. ibound = np.ones((1, 201)) ibound[0, 0] = ibound[0, -1] =", "'GHBs for stress period 1.') # #stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf,", "save time decimate_by_ncells = 1 # by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells]", "using the flopy.utils.binaryfile module. Included with the HeadFile object are several methods that", "from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to the MODFLOW model spd =", "(L2) #h is head (L) #X is the position at which head is", "1: \"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds =", "using the ModelMap class. The following code shows how to use the modelmap", "Basic package (BAS), which is required for every MOD-FLOW model. It contains the", "flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package First, we will", "dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem", "#A is the area perpendicular to flow (L2) #h is head (L) #X", "contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color gradient genu.quick_plot(dem_trans) # plots", "was assumed to be 1 ft/d, #which is consistent with model simulations of", "can be used to quickly initialize the ibound array with values of 1,", "horizontal, approx. bedrock (check Masterson) nlay = 1 # 1 layer model nrow,", "a binary utility that can be used to read the heads. The following", "simulated heads to a binary data output file. We cannot look at these", "like are defined with the Basic package (BAS), which is required for every", "the GHB object, which is of the following type: flopy.modflow.ModflowGhb. The key to", "to 0.5 hrs) perlen = [perlen_days]*nper # length of a stress period; each", "ibound[:,np.isnan(dem_trans)] = 0 # nan cells are inactive genu.quick_plot(ibound) # plots boundary condition:", "type: flopy.modflow.ModflowGhb. The key to creating Flopy transient boundary packages is recognizing that", "= bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1) extent =", "thickness of the seabed deposits was #assumed to be half the thickness of", "since the previous point (need to change the first) perlen[0] = 1 #", "bound_sp1.append([il, ir, ncol - 1, stageright, condright]) ## Only 1 stress period for", "akurnizk \"\"\" import flopy import numpy as np import sys,os import matplotlib.pyplot as", "stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition", "large grid. The commented section below uses the modelmap class from Tutorial 1,", "recharge condition # steady state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3)", "layer=0) #qm = modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5)", "combines the K, A and X terms so that Darcy's law can be", "[perlen_days]*nper # length of a stress period; each item in the matrix is", "C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C", "# headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads", "'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG", "Wed Aug 29 15:47:36 2018 @author: akurnizk \"\"\" import flopy import numpy as", "the area perpendicular to flow (L2) #h is head (L) #X is the", "assumed to be 1 ft/d, #which is consistent with model simulations of similar", "nlay + 1) #%% \"\"\" Time Stepping \"\"\" # Time step parameters total_length", "Ly - delc/2., delc/2.) # headplot = plt.contour(head[0, :, :], levels=levels, extent=extent) #", "{0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied to all stress periods drn =", "0.5 * frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] =", "boundary packages is recognizing that the boundary data is stored in a dictionary", "reduce nrow and ncol on the plot, making it difficult to plot a", "to get hk values at each cell for changing conductance. # condleft =", "values equal to the zero-based stress period number and values equal to the", "# stress period time step, hrs perlen_days = dt/24. # stress period time", "scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results Once", "cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 * (frf[:,", "(L/T) #A is the area perpendicular to flow (L2) #h is head (L)", "head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1) extent = (delr/2., Lx", "# Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an xarray data", "which is of the following type: flopy.modflow.ModflowGhb. The key to creating Flopy transient", "to save time decimate_by_ncells = 1 # by every n cells #dem_X =", "package (BAS), which is required for every MOD-FLOW model. It contains the ibound", "#stageright = mean_sea_level #bound_sp1 = [] #for il in range(nlay): # # Figure", "= fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head =", "steps in a stress period nstp[0] = 1 #Tutorial 2 default time step", "\"\"\" # Time step parameters total_length = 10 # days dt = 6", "drain condition #Darcy's law states that #Q = -KA(h1 - h0)/(X1 - X0)", "= 0.5 * frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :]", "run our MODFLOW model, we can look at the results. MODFLOW writes the", "msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0,", "to 10. # Add LPF package to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf,", "= -C(h1 - h0) #where C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm #", "hydraulic conductivity (L/T) #A is the area perpendicular to flow (L2) #h is", "containing the #boundary. # still using simple conductance land_cells = active_cells & ~np.isnan(dem_trans)", "ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx,", "files mf.write_input() #%% # Run the MODFLOW model success, buff = mf.run_model() #%%", "= np.nan #levels = np.arange(1,10,1) extent = (delr/2., Lx - delr/2., Ly -", "Can calculate cell centers (where heads are calculated), in different coordinates cc,cc_proj,cc_ll =", "nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to the MODFLOW", "general) uses zero-based indexing and supports negative indexing so that row 1 and", "way higher resolution...can decimate it to save time decimate_by_ncells = 1 # by", "freshwater at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with water at", "defined with the Basic package (BAS), which is required for every MOD-FLOW model.", "package (and Python, in general) uses zero-based indexing and supports negative indexing so", "nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore cells are inactive ibound[0,dem_trans<mean_sea_level]", "mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan", "can can be accessed using the ModelMap class. The following code shows how", "the model results.: \"\"\" # headfile and budget file objects already created #", "#Conductance combines the K, A and X terms so that Darcy's law can", "condition # steady state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) #", "recognizing that the boundary data is stored in a dictionary with key values", "be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to 10 -", "Sea Level (MSL) in meters at closest NOAA station for stages #stageleft =", "in meters # Define inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs =", "section below uses the modelmap class from Tutorial 1, followed by use of", "get_data() will return a three-dimensional head array for the specified time * get_ts()", "areas on Cape Cod (Masterson and #others, 1998). In the area occupied by", "period nstp[0] = 1 #Tutorial 2 default time step parameters #nper = 3", "dem_vals = rastu.read_griddata(dem_fname) # Know that dem is way higher resolution...can decimate it", "# in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model", "at which head is measured (L) #Conductance combines the K, A and X", "for ir in range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir,", "thickness for cases of unconfined flow. ibound = np.ones((1, 201)) ibound[0, 0] =", "-100 # if bottom of model is horizontal, approx. bedrock (check Masterson) nlay", "1 and column 201, can be referenced as [0,0], and [0,−1], respectively. Although", "a text editor, but flopy has a binary utility that can be used", ":], interpolation='nearest', # extent=(0, Lx, 0, Ly)) y, x, z = dis.get_node_coordinates() X,", "= {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the outputs into", "delc/2., Ly - delc/2.) print('Levels: ', levels) print('Extent: ', extent) # Make the", "1000. # (modify 1000 to actual conductance) bound_sp1 = [] stress_period_data = {0:", "# Need to fix grid to have fewer rows and columns #cs =", "offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for everything less", "= 1 #nrow = 10 #ncol = 10 #delr = Lx/ncol #delc =", "201, can be referenced as [0,0], and [0,−1], respectively. Although this simulation is", "in other areas on Cape Cod (Masterson and #others, 1998). In the area", "dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is", "botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for the BAS (basic)", "genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) #", "= 6 # stress period time step, hrs perlen_days = dt/24. # stress", "= np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 * (frf[:, :, 0:ncol-1] +", "False] #%% # Create the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow,", "can read heads from the MODFLOW binary output file, using the flopy.utils.binaryfile module.", "then set the ibound value for the first and last columns to −1.", "= Lx/ncol #delc = Ly/nrow #delv = (ztop - zbot) / nlay #botm", "hk1[0,0,0] * (stageleft - zbot) * delc # condright = hk1[0,0,0] * (stageright", "heads with a text editor, but flopy has a binary utility that can", "time step, days nper = int(total_length/perlen_days) # the number of stress periods in", "in range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol -", "the head for fixed-head cells (where ibound is negative), and as a starting", "times contained in the binary head file * get_data() will return a three-dimensional", "strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with water at sea level genu.quick_plot(strt) #", "cannot look at these heads with a text editor, but flopy has a", "10 #ncol = 10 #delr = Lx/ncol #delc = Ly/nrow #delv = (ztop", "flows to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5", "1 model domain and grid definition #Lx = 1000. #Ly = 1000. #ztop", "also has some pre-canned plotting capabilities can can be accessed using the ModelMap", "1, stageright, condright]) ## Only 1 stress period for steady-state model #print('Adding ',", "#steady = [True, False, False] #%% # Create the discretization (DIS) object dis", "bedrock (check Masterson) nlay = 1 # 1 layer model nrow, ncol =", "Flow right face and flow front face already extracted ##%% ##Create the plot", "coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same", "= flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm =", "dt = 6 # stress period time step, hrs perlen_days = dt/24. #", "step, hrs perlen_days = dt/24. # stress period time step, days nper =", "(aliased as np) can be used to quickly initialize the ibound array with", "* fff[0, :, :] # Make the plot fig = plt.figure(figsize=(10, 10)) ax", "#was set to 0.1 ft/d. The thickness of the seabed deposits was #assumed", "of seabed deposits (ft). #The vertical hydraulic conductivity (K) of the seabed #deposits", "strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells", "and column 201, can be referenced as [0,0], and [0,−1], respectively. Although this", "binary head file and create a plot of simulated heads for layer 1:", "inactive genu.quick_plot(ibound) # plots boundary condition: 1 is above mean sea level (msl),", "cell centers (where heads are calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) #", "consistent with model simulations of similar coastal #discharge areas in other areas on", "= {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's", "in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates", "OC package to the MODFLOW model spd = {(0, 0): ['print head', 'print", "int(total_length/perlen_days) # the number of stress periods in the simulation nstp_default = dt/0.5", "The commented section below uses the modelmap class from Tutorial 1, followed by", "condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19 - creates matrix", "- X0) #Where Q is the flow (L3/T) #K is the hydraulic conductivity", "specified cell Using these methods, we can create head plots and hydrographs from", "ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package First, we will create the GHB", "key to creating Flopy transient boundary packages is recognizing that the boundary data", "conductance]: Datums for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list", "#Where Q is the flow (L3/T) #K is the hydraulic conductivity (L/T) #A", "genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row,", "other areas on Cape Cod (Masterson and #others, 1998). In the area occupied", "#%% \"\"\" Flopy also has some pre-canned plotting capabilities can can be accessed", "# top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for the", "-1 # fixed head for everything less than msl ibound[:,np.isnan(dem_trans)] = 0 #", "-qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\"", "# set first step as steady state steady = [False]*nper steady[0] = True", "dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper,", "1000. #ztop = 0. #zbot = -50. #nlay = 1 #nrow = 10", "to allow averaging to reduce nrow and ncol on the plot, making it", "which cells are active (value is positive), inactive (value is 0), or fixed", "NOAA station #%% # Example of making a MODFLOW-like grid from a shapefile", "hydraulic conductance of the seabed (ft2/d); #K is vertical hydraulic conductivity of seabed", "In the area occupied by Salt Pond and Nauset #Marsh, it was assumed", "as genu from cgw.utils import feature_utils as shpu from cgw.utils import raster_utils as", "= plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:, 0,", "drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition # steady state, units", "projection as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%%", "station #%% # Example of making a MODFLOW-like grid from a shapefile data_dir", "are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for everything less than msl", "zbot, nlay + 1) #%% \"\"\" Time Stepping \"\"\" # Time step parameters", "strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start with freshwater at surface elevation", "(dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be", "condition: 1 is above mean sea level (msl), 0 is msl, -1 is", "is negative). The numpy package (aliased as np) can be used to quickly", "Variables for the BAS (basic) package # Added 5/28/19 \"\"\" Active cells and", "hk1[:,:,:]=10. # everything set to 10 - use data? calculate? vka1 = np.ones((nlay,nrow,ncol),", "is measured (L) #Conductance combines the K, A and X terms so that", "parameters #nper = 3 #perlen = [1, 100, 100] #nstp = [1, 100,", "sea level genu.quick_plot(strt) # plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%%", "#quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, #", "plots #Print statistics print('Head statistics') print(' min: ', head.min()) print(' max: ', head.max())", "#perlen = [1, 100, 100] #nstp = [1, 100, 100] #steady = [True,", "#which is consistent with model simulations of similar coastal #discharge areas in other", "the modelmap class to plot boundary conditions (IBOUND), plot the grid, plot head", "in a stress period nstp[0] = 1 #Tutorial 2 default time step parameters", "#The vertical hydraulic conductivity (K) of the seabed #deposits in most of the", "of 1, and then set the ibound value for the first and last", "and supports negative indexing so that row 1 and column 1, and row", "plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0,", "using simple conductance land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols =", "it to save time decimate_by_ncells = 1 # by every n cells #dem_X", "on Wed Aug 29 15:47:36 2018 @author: akurnizk \"\"\" import flopy import numpy", "Time Stepping \"\"\" # Time step parameters total_length = 10 # days dt", "budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG package to the", "= ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype)", "the binary head file and create a plot of simulated heads for layer", "Results Now that we have successfully built and run our MODFLOW model, we", "= 1 # by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells]", "print(swt.namefile) mean_sea_level = 0.843 # in meters at closest NOAA station #%% #", "#where C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 #", "to be 1 ft/d, #which is consistent with model simulations of similar coastal", "dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to model coordinates with linear interpolation trans_dict", "1:] = 0.5 * (frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :,", "interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same projection as model", "using modelmap \"\"\" ## Flow right face and flow front face already extracted", "is length of the model cell containing the seabed (ft); #and #M is", "print('Head statistics') print(' min: ', head.min()) print(' max: ', head.max()) print(' std: ',", "#C is hydraulic conductance of the seabed (ft2/d); #K is vertical hydraulic conductivity", "of stress periods in the simulation nstp_default = dt/0.5 # stress period time", "zero-based stress period number and values equal to the boundary conditions for that", "= dt/24. # stress period time step, days nper = int(total_length/perlen_days) # the", "= bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11)", "expressed as #Q = -C(h1 - h0) #where C is the conductance (L2/T)", "#dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2", "(frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :, 0] = 0.5 *", "the values can be a two-dimensional nested list of [layer, row, column, stage,", "np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip,", "stageleft, condleft]) # bound_sp1.append([il, ir, ncol - 1, stageright, condright]) ## Only 1", "water at sea level genu.quick_plot(strt) # plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound,", "out looping through hk1 array to get hk values at each cell for", "botm=botm) # Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr,", "- zbot) / nlay botm = zbot # Tutorial 1 model domain and", "# Transform dem to model coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj}", "vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') hds =", "starting heads still need to be specified. They are used as the head", "conductivity (K) of the seabed #deposits in most of the study area was", "set the ibound value for the first and last columns to −1. The", "mean_sea_level # start with water at sea level genu.quick_plot(strt) # plots starting condition", "use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to 10.", "Figure out looping through hk1 array to get hk values at each cell", "return a time series array [ntimes, headval] for the specified cell Using these", "with the HeadFile object are several methods that we will use here: *", ":, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png')", "package to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW", "h0)/(X1 - X0) #Where Q is the flow (L3/T) #K is the hydraulic", "0. #zbot = -50. #nlay = 1 #nrow = 10 #ncol = 10", "flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head =", "Cod (Masterson and #others, 1998). In the area occupied by Salt Pond and", "conductivity of seabed deposits #(ft/d); #W is width of the model cell containing", "plot the grid, plot head contours, and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10))", "step parameters total_length = 10 # days dt = 6 # stress period", "time length (to better interpolate tidal changes, set to 0.5 hrs) perlen =", "swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in meters at closest", "{(0, 0): ['print head', 'print budget', 'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf,", "model coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in", "of a stress period; each item in the matrix is the amount #", "# days dt = 6 # stress period time step, hrs perlen_days =", "through hk1 array to get hk values at each cell for changing conductance.", "implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to 10 - use", "land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied to all stress", "create modflow model object modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname,", "Ly)) y, x, z = dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip =", "every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] #", "nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object when transient", "= rastu.load_geotif(dem_fname) # da is an xarray data array dem_vals = dem_da.values.squeeze() #dem_X,", "(value is 0), or fixed head (value is negative). The numpy package (aliased", "# the number of stress periods in the simulation nstp_default = dt/0.5 #", "extent=extent) # headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots", "https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to the MODFLOW model spd = {(0,", "head is measured (L) #Conductance combines the K, A and X terms so", "the vertical hydraulic conductivity #was set to 0.1 ft/d. The thickness of the", "column 201, can be referenced as [0,0], and [0,−1], respectively. Although this simulation", "simulated heads for layer 1: \"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import", "position at which head is measured (L) #Conductance combines the K, A and", "(L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C = KWL/M where #C", "landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied", "np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay,", "ibound[0, -1] = -1 \"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] =", "1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx, 0, Ly)) y, x,", "= {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value (see", "hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1) extent = (delr/2., Lx - delr/2.,", "to creating Flopy transient boundary packages is recognizing that the boundary data is", "plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times()", "nlay #botm = np.linspace(ztop, zbot, nlay + 1) #%% \"\"\" Time Stepping \"\"\"", "DIS object when transient conditions are implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow,", "of the seabed deposits was #assumed to be half the thickness of the", "#') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example", "(basic) package # Added 5/28/19 \"\"\" Active cells and the like are defined", "grid, plot head contours, and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax =", "stress period 1.') # #stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #", "column, stage, conductance]: Datums for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" #", "https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress period 1 # Using Mean Sea", "delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object when transient conditions are implemented", "have successfully built and run our MODFLOW model, we can look at the", "levels) print('Extent: ', extent) # Make the plots #Print statistics print('Head statistics') print('", "x, z = dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip,", "plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color gradient genu.quick_plot(dem_trans) # plots elevations #%%", "Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress period 1 # Using", "KWL/M where #C is hydraulic conductance of the seabed (ft2/d); #K is vertical", "= cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\"", "Make the plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal')", "set to 10. # Add LPF package to the MODFLOW model lpf =", "of the following type: flopy.modflow.ModflowGhb. The key to creating Flopy transient boundary packages", "#plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0,", "the heads. The following statements will read the binary head file and create", "rows and columns #cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png')", "[0,0], and [0,−1], respectively. Although this simulation is for steady flow, starting heads", "rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package", "for every MOD-FLOW model. It contains the ibound array, which is used to", "plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color gradient", "uses zero-based indexing and supports negative indexing so that row 1 and column", "to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 *", "the position at which head is measured (L) #Conductance combines the K, A", "followed by use of the plotting from the Henry Problem. \"\"\" #modelmap =", "# plots elevations #%% \"\"\" Flopy also has some pre-canned plotting capabilities can", "#Darcy's law states that #Q = -KA(h1 - h0)/(X1 - X0) #Where Q", "Now that we have successfully built and run our MODFLOW model, we can", "#bound_sp1 = [] #for il in range(nlay): # # Figure out looping through", "of model is horizontal, approx. bedrock (check Masterson) nlay = 1 # 1", "array for the specified time * get_ts() will return a time series array", "face already extracted ##%% ##Create the plot #f = plt.figure() #plt.subplot(1, 1, 1,", "time step parameters #nper = 3 #perlen = [1, 100, 100] #nstp =", "head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt)", "conductivity #was set to 0.1 ft/d. The thickness of the seabed deposits was", "(fff[0:nlay-1, :, :] + fff[1:nlay, :, :]) qy_avg[0, :, :] = 0.5 *", "of the seabed #deposits in most of the study area was assumed to", "meters # Define inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict)", "raster_utils as rastu # Assign name and create modflow model object modelname =", "#%% # Create the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol,", "the ModelMap class. The following code shows how to use the modelmap class", "= 3 #perlen = [1, 100, 100] #nstp = [1, 100, 100] #steady", ":, :] = 0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay, :, :]) qy_avg[0,", "\\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an xarray data array dem_vals =", "ibound[:,~active_cells] = 0 # far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 #", "to be half the thickness of the model cell containing the #boundary. #", "#boundary. # still using simple conductance land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level)", "ncol = cc[0].shape # to use when cheq_griddev is implemented delr = cell_spacing", "allow averaging to reduce nrow and ncol on the plot, making it difficult", "& ~np.isnan(dem_trans)] = active_dem_heights # start with freshwater at surface elevation strt[0, dem_trans<mean_sea_level]", "0, :], interpolation='nearest', # extent=(0, Lx, 0, Ly)) y, x, z = dis.get_node_coordinates()", "Make list for stress period 1 # Using Mean Sea Level (MSL) in", "1 #nrow = 10 #ncol = 10 #delr = Lx/ncol #delc = Ly/nrow", "times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell centers", "= np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore cells are", "- 1, stageright, condright]) ## Only 1 stress period for steady-state model #print('Adding", "aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0,", "array to get hk values at each cell for changing conductance. # condleft", "iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip],", "delc/2.) print('Levels: ', levels) print('Extent: ', extent) # Make the plots #Print statistics", "hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to 10 - use data?", "cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active cells in the model", "supports negative indexing so that row 1 and column 1, and row 1", "= modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head)", "statistics') print(' min: ', head.min()) print(' max: ', head.max()) print(' std: ', head.std())", "\"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1,", "0, Ly)) y, x, z = dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip", "step steady state nstp = [nstp_default]*nper # number of time steps in a", "= flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's law states that #Q", "be accessed using the ModelMap class. The following code shows how to use", "on Masterson, 2004) conductance = 1000. # (modify 1000 to actual conductance) bound_sp1", "= os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid cell spacing in meters #", "0.5 * fff[0, :, :] # Make the plot fig = plt.figure(figsize=(10, 10))", "#%% \"\"\" Post-Processing the Results Once again, we can read heads from the", "np.ones((1, 201)) ibound[0, 0] = ibound[0, -1] = -1 \"\"\" ibound = np.ones((nlay,", "following type: flopy.modflow.ModflowGhb. The key to creating Flopy transient boundary packages is recognizing", "the zero-based stress period number and values equal to the boundary conditions for", "modelmap.plot_grid() # Need to fix grid to have fewer rows and columns #cs", "stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition # steady", "DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) #", "make transform list # Can calculate cell centers (where heads are calculated), in", "# Example of making a MODFLOW-like grid from a shapefile data_dir = r'E:\\ArcGIS'", "\"\"\" import flopy import numpy as np import sys,os import matplotlib.pyplot as plt", "ir, ncol - 1, stageright, condright]) ## Only 1 stress period for steady-state", "Make the plots #Print statistics print('Head statistics') print(' min: ', head.min()) print(' max:", "for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all", "MODFLOW writes the simulated heads to a binary data output file. We cannot", "z = dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip],", "most of the study area was assumed to be 1 ft/d, #which is", "model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package", "be specified. They are used as the head for fixed-head cells (where ibound", "are calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define", "cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu from cgw.utils import", "6 # stress period time step, hrs perlen_days = dt/24. # stress period", "a MODFLOW-like grid from a shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing", "of simulated heads for layer 1: \"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1", "for that stress period. For a GHB the values can be a two-dimensional", "cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active", "use when cheq_griddev is implemented delr = cell_spacing delc = cell_spacing delv =", "plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19 -", "(stageleft - zbot) * delc # condright = hk1[0,0,0] * (stageright - zbot)", "look at the results. MODFLOW writes the simulated heads to a binary data", "r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843", "calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to 10. # Add", "Ly/nrow #delv = (ztop - zbot) / nlay #botm = np.linspace(ztop, zbot, nlay", "Use model_polygon to define active cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells", "cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff", "extent = (delr/2., Lx - delr/2., Ly - delc/2., delc/2.) # headplot =", "we can look at the results. MODFLOW writes the simulated heads to a", "bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1) extent = (delr/2.,", "modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f',", "= land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied to all", "(L) #Conductance combines the K, A and X terms so that Darcy's law", "again, we can read heads from the MODFLOW binary output file, using the", "conductance = 1000. # (modify 1000 to actual conductance) bound_sp1 = [] stress_period_data", "resolution...can decimate it to save time decimate_by_ncells = 1 # by every n", "plot #f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf,", "will read the binary head file and create a plot of simulated heads", "Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space", "Pond and Nauset #Marsh, it was assumed that there were thick deposits of", "rastu.read_griddata(dem_fname) # Know that dem is way higher resolution...can decimate it to save", "and grid definition #Lx = 1000. #Ly = 1000. #ztop = 0. #zbot", "and row 1 and column 201, can be referenced as [0,0], and [0,−1],", ":, 1:ncol]) qx_avg[:, :, 0] = 0.5 * frf[:, :, 0] qy_avg =", "uses the modelmap class from Tutorial 1, followed by use of the plotting", "values equal to the boundary conditions for that stress period. For a GHB", "land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec =", "import sys,os import matplotlib.pyplot as plt # Location of BitBucket folder containing cgw", "modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head,", "fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:,", "[m]') #%% Example of loading DEM data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif')", "# nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for the BAS (basic) package", "the flow (L3/T) #K is the hydraulic conductivity (L/T) #A is the area", "at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with water at sea", "0.843 # in meters at closest NOAA station #%% # Example of making", "= -100 # if bottom of model is horizontal, approx. bedrock (check Masterson)", "layer 1: \"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds", "a shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model", "model. It contains the ibound array, which is used to specify which cells", "= dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start with", "and values equal to the boundary conditions for that stress period. For a", "MODFLOW-like grid from a shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing =", "Lx, 0, Ly)) y, x, z = dis.get_node_coordinates() X, Y = np.meshgrid(x, y)", "object modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt =", "the simulation nstp_default = dt/0.5 # stress period time step divided by step", "(stageright - zbot) * delc # for ir in range(nrow): # bound_sp1.append([il, ir,", "# from Masterson, 2004 # C = KWL/M where #C is hydraulic conductance", "= dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] =", "for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname)", "indexing so that row 1 and column 1, and row 1 and column", "strt=strt) #%% # added 3/8/19 - creates matrix where hydraulic conductivities (hk =", "on Cape Cod (Masterson and #others, 1998). In the area occupied by Salt", "[] stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain", "to quickly initialize the ibound array with values of 1, and then set", "from cgw.utils import raster_utils as rastu # Assign name and create modflow model", "1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1]) levels =", "difficult to plot a large grid. The commented section below uses the modelmap", "writes the simulated heads to a binary data output file. We cannot look", "# Load data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times()", "#%% # Example of making a MODFLOW-like grid from a shapefile data_dir =", "hrs) perlen = [perlen_days]*nper # length of a stress period; each item in", "#K is the hydraulic conductivity (L/T) #A is the area perpendicular to flow", "[out_proj,[xshift,yshift],min_angle] # make transform list # Can calculate cell centers (where heads are", "ft/d, #which is consistent with model simulations of similar coastal #discharge areas in", "list of times contained in the binary head file * get_data() will return", "(<NAME>, U.S. Geological Survey, #oral commun., 2002) and the vertical hydraulic conductivity #was", "heads are calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to", "be used to read the heads. The following statements will read the binary", "make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels =", "head contours, and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1,", "binary head file * get_data() will return a three-dimensional head array for the", "dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights #", "##%% ##Create the plot #f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # #", "aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest', extent=(0, Lx, 0, Ly)) ax.set_title('Simulated Heads')", "landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied to", "Time step parameters total_length = 10 # days dt = 6 # stress", "of times contained in the binary head file * get_data() will return a", "−1. The numpy package (and Python, in general) uses zero-based indexing and supports", "\"\"\" Again, commented out section using modelmap \"\"\" ## Flow right face and", "and run our MODFLOW model, we can look at the results. MODFLOW writes", "BitBucket folder containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils", "= flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in", "da is an xarray data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals =", "0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay, :, :]) qy_avg[0, :, :] =", "::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the", "#ax[1].set_ylabel('Y [m]') #%% Example of loading DEM data for that area dem_fname =", "specify which cells are active (value is positive), inactive (value is 0), or", "area perpendicular to flow (L2) #h is head (L) #X is the position", "plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots", "hk values at each cell for changing conductance. # condleft = hk1[0,0,0] *", "= 'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4')", "to specify which cells are active (value is positive), inactive (value is 0),", "the seabed (ft2/d); #K is vertical hydraulic conductivity of seabed deposits #(ft/d); #W", "specified. They are used as the head for fixed-head cells (where ibound is", "fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN',", "fff[0, :, :] # Make the plot fig = plt.figure(figsize=(10, 10)) ax =", "', head.min()) print(' max: ', head.max()) print(' std: ', head.std()) \"\"\" Again, commented", "actual conductance) bound_sp1 = [] stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data)", "with key values equal to the zero-based stress period number and values equal", "the specified time * get_ts() will return a time series array [ntimes, headval]", "1.') # #stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single", "to the MODFLOW model spd = {(0, 0): ['print head', 'print budget', 'save", "qy_avg[0, :, :] = 0.5 * fff[0, :, :] # Make the plot", "utf-8 -*- \"\"\" Created on Wed Aug 29 15:47:36 2018 @author: akurnizk \"\"\"", "FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't seem to be able", "head.min()) print(' max: ', head.max()) print(' std: ', head.std()) \"\"\" Again, commented out", "model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax", "as #Q = -C(h1 - h0) #where C is the conductance (L2/T) #", "\"\"\" # headfile and budget file objects already created # Setup contour parameters", "ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf,", "from Masterson, 2004 # C = KWL/M where #C is hydraulic conductance of", "output file, using the flopy.utils.binaryfile module. Included with the HeadFile object are several", "flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB',", "sea level (msl), 0 is msl, -1 is under msl. strt = np.ones((nlay,", "of making a MODFLOW-like grid from a shapefile data_dir = r'E:\\ArcGIS' shp_fname =", "utility that can be used to read the heads. The following statements will", "botm=botm[1:]) # Tutorial 2 DIS object when transient conditions are implemented # dis", "1 stress period for steady-state model #print('Adding ', len(bound_sp1), 'GHBs for stress period", "qx_avg[:, :, 1:] = 0.5 * (frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol])", "simulation nstp_default = dt/0.5 # stress period time step divided by step time", "our MODFLOW model, we can look at the results. MODFLOW writes the simulated", "nrow and ncol on the plot, making it difficult to plot a large", "still using simple conductance land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols", "package (aliased as np) can be used to quickly initialize the ibound array", "# of elapsed time since the previous point (need to change the first)", "1 ft/d, #which is consistent with model simulations of similar coastal #discharge areas", "steady = [False]*nper steady[0] = True # first step steady state nstp =", "flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to the", "cgw.utils import feature_utils as shpu from cgw.utils import raster_utils as rastu # Assign", "Active cells and the like are defined with the Basic package (BAS), which", "0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show()", "5/28/19 \"\"\" Active cells and the like are defined with the Basic package", "mean_sea_level #stageright = mean_sea_level #bound_sp1 = [] #for il in range(nlay): # #", "a time series array [ntimes, headval] for the specified cell Using these methods,", "contour parameters (levels already set) extent = (delr/2., Lx - delr/2., delc/2., Ly", "0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1, :,", "(delr/2., Lx - delr/2., Ly - delc/2., delc/2.) # headplot = plt.contour(head[0, :,", "Add drain condition #Darcy's law states that #Q = -KA(h1 - h0)/(X1 -", "#plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME>", "boundary condition: 1 is above mean sea level (msl), 0 is msl, -1", "flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to fix grid", "qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 * (frf[:, :, 0:ncol-1]", "linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same projection as", "a dictionary with key values equal to the zero-based stress period number and", "commun., 2002) and the vertical hydraulic conductivity #was set to 0.1 ft/d. The", "& (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will", "# condleft = hk1[0,0,0] * (stageleft - zbot) * delc # condright =", "- delc/2., delc/2.) # headplot = plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot", "calculate cell centers (where heads are calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform)", "# Figure out looping through hk1 array to get hk values at each", "thick deposits of lowpermeability #material (<NAME>, U.S. Geological Survey, #oral commun., 2002) and", "in same projection as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan", "the ibound array with values of 1, and then set the ibound value", "GHB object, which is of the following type: flopy.modflow.ModflowGhb. The key to creating", "the plot #f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # # #modelmap =", "Level (MSL) in meters at closest NOAA station for stages #stageleft = mean_sea_level", "each item in the matrix is the amount # of elapsed time since", "seabed (ft2/d); #K is vertical hydraulic conductivity of seabed deposits #(ft/d); #W is", "= [perlen_days]*nper # length of a stress period; each item in the matrix", "far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for everything", "::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025)", "perlen[0] = 1 # set first step as steady state steady = [False]*nper", "used to specify which cells are active (value is positive), inactive (value is", "fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't seem", "the MODFLOW model input files mf.write_input() #%% # Run the MODFLOW model success,", "color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results", "similar coastal #discharge areas in other areas on Cape Cod (Masterson and #others,", "simulations of similar coastal #discharge areas in other areas on Cape Cod (Masterson", "width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results Once again, we can read", "to 10 - use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything", "out section using modelmap \"\"\" ## Flow right face and flow front face", "* (frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :, 0] = 0.5", "Datums for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for", "# Write the MODFLOW model input files mf.write_input() #%% # Run the MODFLOW", "# #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ## lc = modelmap.plot_grid()", "= modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver", "genu.quick_plot(dem_trans) #%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot =", "15:47:36 2018 @author: akurnizk \"\"\" import flopy import numpy as np import sys,os", "len(bound_sp1), 'GHBs for stress period 1.') # #stress_period_data = {0: bound_sp1} #ghb =", "# Add LPF package to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1,", "results.: \"\"\" # headfile and budget file objects already created # Setup contour", "nlay botm = zbot # Tutorial 1 model domain and grid definition #Lx", "fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1])", "the specified cell Using these methods, we can create head plots and hydrographs", "(dem_trans - zbot) / nlay botm = zbot # Tutorial 1 model domain", "100, 100] #nstp = [1, 100, 100] #steady = [True, False, False] #%%", "{0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's law", "\"\"\" Active cells and the like are defined with the Basic package (BAS),", "the simulated heads to a binary data output file. We cannot look at", "below uses the modelmap class from Tutorial 1, followed by use of the", "cells are active (value is positive), inactive (value is 0), or fixed head", "can look at the results. MODFLOW writes the simulated heads to a binary", "head[head<-100] = np.nan #levels = np.arange(1,10,1) extent = (delr/2., Lx - delr/2., Ly", "that #Q = -KA(h1 - h0)/(X1 - X0) #Where Q is the flow", "state nstp = [nstp_default]*nper # number of time steps in a stress period", "0] = 0.5 * frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :,", "deposits (ft). #The vertical hydraulic conductivity (K) of the seabed #deposits in most", "cells and the like are defined with the Basic package (BAS), which is", "everything less than msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells are inactive genu.quick_plot(ibound)", "~np.isnan(dem_trans)] = active_dem_heights # start with freshwater at surface elevation strt[0, dem_trans<mean_sea_level] =", "read heads from the MODFLOW binary output file, using the flopy.utils.binaryfile module. Included", "(L3/T) #K is the hydraulic conductivity (L/T) #A is the area perpendicular to", "DEM data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da", "surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with water at sea level", "We cannot look at these heads with a text editor, but flopy has", "MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model input files", "dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 * (frf[:, :, 0:ncol-1] + frf[:, :,", "head (value is negative). The numpy package (aliased as np) can be used", "built and run our MODFLOW model, we can look at the results. MODFLOW", "Load data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration", "#qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to fix grid to have", "= flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model input files mf.write_input() #%% #", "#dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that dem is way higher resolution...can", "headval] for the specified cell Using these methods, we can create head plots", "the first and last columns to −1. The numpy package (and Python, in", "Add LPF package to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53)", "#X is the position at which head is measured (L) #Conductance combines the", "steady state steady = [False]*nper steady[0] = True # first step steady state", "is the hydraulic conductivity (L/T) #A is the area perpendicular to flow (L2)", "grid. The commented section below uses the modelmap class from Tutorial 1, followed", "is 0), or fixed head (value is negative). The numpy package (aliased as", "the saturated thickness for cases of unconfined flow. ibound = np.ones((1, 201)) ibound[0,", "flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG package to the MODFLOW model pcg", "set first step as steady state steady = [False]*nper steady[0] = True #", "nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS object #dis =", "bottom of model is horizontal, approx. bedrock (check Masterson) nlay = 1 #", "# headplot = plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot = plt.contour(head[0, :,", "0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :, 0] = 0.5 * frf[:, :,", "the seabed (ft); #L is length of the model cell containing the seabed", "', levels) print('Extent: ', extent) # Make the plots #Print statistics print('Head statistics')", ":, 0] = 0.5 * frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:,", "the model cell containing the #boundary. # still using simple conductance land_cells =", "0.5 hrs) perlen = [perlen_days]*nper # length of a stress period; each item", "equal to the boundary conditions for that stress period. For a GHB the", "100, 100] #steady = [True, False, False] #%% # Create the discretization (DIS)", "is above mean sea level (msl), 0 is msl, -1 is under msl.", "os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid cell spacing in meters # Define", "at closest NOAA station for stages #stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1", "head array for the specified time * get_ts() will return a time series", "#stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1 = [] #for il in range(nlay):", "units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% #", "amount # of elapsed time since the previous point (need to change the", "a starting point to compute the saturated thickness for cases of unconfined flow.", "+ frf[:, :, 1:ncol]) qx_avg[:, :, 0] = 0.5 * frf[:, :, 0]", "', extent) # Make the plots #Print statistics print('Head statistics') print(' min: ',", "= dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to", "#delr = Lx/ncol #delc = Ly/nrow #delv = (ztop - zbot) / nlay", "grid to have fewer rows and columns #cs = modelmap.contour_array(head, levels=levels) #quiver =", "set to 0.5 hrs) perlen = [perlen_days]*nper # length of a stress period;", "in meters at closest NOAA station for stages #stageleft = mean_sea_level #stageright =", "The key to creating Flopy transient boundary packages is recognizing that the boundary", "delv = (dem_trans - zbot) / nlay botm = zbot # Tutorial 1", "RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned", "averaging to reduce nrow and ncol on the plot, making it difficult to", "length (to better interpolate tidal changes, set to 0.5 hrs) perlen = [perlen_days]*nper", "+ fff[1:nlay, :, :]) qy_avg[0, :, :] = 0.5 * fff[0, :, :]", "#genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in", "1) #%% \"\"\" Time Stepping \"\"\" # Time step parameters total_length = 10", "state steady = [False]*nper steady[0] = True # first step steady state nstp", "bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol - 1, stageright, condright])", "Cape Cod (Masterson and #others, 1998). In the area occupied by Salt Pond", "#material (<NAME>, U.S. Geological Survey, #oral commun., 2002) and the vertical hydraulic conductivity", "changing conductance. # condleft = hk1[0,0,0] * (stageleft - zbot) * delc #", "that the boundary data is stored in a dictionary with key values equal", "# length of a stress period; each item in the matrix is the", "= ibound[0, -1] = -1 \"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells]", "point to compute the saturated thickness for cases of unconfined flow. ibound =", "spd = {(0, 0): ['print head', 'print budget', 'save head', 'save budget']} oc", "Nauset #Marsh, it was assumed that there were thick deposits of lowpermeability #material", "hydraulic conductivities (hk = horiz, vk = vert) can be implemented hk1 =", "max: ', head.max()) print(' std: ', head.std()) \"\"\" Again, commented out section using", "file * get_data() will return a three-dimensional head array for the specified time", "np.linspace(ztop, zbot, nlay + 1) #%% \"\"\" Time Stepping \"\"\" # Time step", "fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :],", "data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that", "[0,−1], respectively. Although this simulation is for steady flow, starting heads still need", "to fix grid to have fewer rows and columns #cs = modelmap.contour_array(head, levels=levels)", "= dt/0.5 # stress period time step divided by step time length (to", "zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1,", "model cell containing the seabed (ft); #L is length of the model cell", "Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2,", "are several methods that we will use here: * get_times() will return a", "delr = cell_spacing delc = cell_spacing delv = (dem_trans - zbot) / nlay", "1 is above mean sea level (msl), 0 is msl, -1 is under", "perlen_days = dt/24. # stress period time step, days nper = int(total_length/perlen_days) #", "the seabed deposits was #assumed to be half the thickness of the model", "#quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing SEAWAT)", "is hydraulic conductance of the seabed (ft2/d); #K is vertical hydraulic conductivity of", "calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active", "= [] #for il in range(nlay): # # Figure out looping through hk1", "modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc,", "the MODFLOW binary output file, using the flopy.utils.binaryfile module. Included with the HeadFile", "single conductance value (see drain for modification based on Masterson, 2004) conductance =", "= flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC package to", "section using modelmap \"\"\" ## Flow right face and flow front face already", "= plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times =", "ncol on the plot, making it difficult to plot a large grid. The", "= np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW", "# steady state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from", "buff = mf.run_model() #%% \"\"\" Post-Processing the Results Now that we have successfully", "fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8,", "-*- \"\"\" Created on Wed Aug 29 15:47:36 2018 @author: akurnizk \"\"\" import", "lowpermeability #material (<NAME>, U.S. Geological Survey, #oral commun., 2002) and the vertical hydraulic", "that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) #", "if dem in same projection as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000]", "the Results Once again, we can read heads from the MODFLOW binary output", "* delc # condright = hk1[0,0,0] * (stageright - zbot) * delc #", "', len(bound_sp1), 'GHBs for stress period 1.') # #stress_period_data = {0: bound_sp1} #ghb", "print(' std: ', head.std()) \"\"\" Again, commented out section using modelmap \"\"\" ##", "(value is positive), inactive (value is 0), or fixed head (value is negative).", "is the amount # of elapsed time since the previous point (need to", "top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for the BAS", "#Q = -C(h1 - h0) #where C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm", "From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal')", "= mean_sea_level # start with water at sea level genu.quick_plot(strt) # plots starting", "contours, and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1,", "headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results Once again, we", "the grid, plot head contours, and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax", "a three-dimensional head array for the specified time * get_ts() will return a", "Setup contour parameters (levels already set) extent = (delr/2., Lx - delr/2., delc/2.,", "seabed deposits was #assumed to be half the thickness of the model cell", "# da is an xarray data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals", "areas in other areas on Cape Cod (Masterson and #others, 1998). In the", "used as the head for fixed-head cells (where ibound is negative), and as", "# Added 5/28/19 \"\"\" Active cells and the like are defined with the", "::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2,", "import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head", "bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's law states", "coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading DEM data for", "conductivities (hk = horiz, vk = vert) can be implemented hk1 = np.ones((nlay,nrow,ncol),", "MODFLOW model, we can look at the results. MODFLOW writes the simulated heads", "front face already extracted ##%% ##Create the plot #f = plt.figure() #plt.subplot(1, 1,", "extent) # Make the plots #Print statistics print('Head statistics') print(' min: ', head.min())", "- zbot) / nlay #botm = np.linspace(ztop, zbot, nlay + 1) #%% \"\"\"", "#print('Adding ', len(bound_sp1), 'GHBs for stress period 1.') # #stress_period_data = {0: bound_sp1}", "* frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5", "and ncol on the plot, making it difficult to plot a large grid.", "dem_trans<mean_sea_level] = mean_sea_level # start with water at sea level genu.quick_plot(strt) # plots", "Post-Processing the Results Once again, we can read heads from the MODFLOW binary", "np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom of model is", "(msl), 0 is msl, -1 is under msl. strt = np.ones((nlay, nrow, ncol),", "seabed (ft); #and #M is thickness of seabed deposits (ft). #The vertical hydraulic", "coding: utf-8 -*- \"\"\" Created on Wed Aug 29 15:47:36 2018 @author: akurnizk", "delc = cell_spacing delv = (dem_trans - zbot) / nlay botm = zbot", "centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 * (frf[:, :,", "plot a large grid. The commented section below uses the modelmap class from", "already extracted ##%% ##Create the plot #f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal')", "= 0 # far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed", "for steady flow, starting heads still need to be specified. They are used", "and create modflow model object modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf =", "vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to 10. # Add LPF", "PCG package to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the", "(check Masterson) nlay = 1 # 1 layer model nrow, ncol = cc[0].shape", "The numpy package (aliased as np) can be used to quickly initialize the", "ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol - 1, stageright, condright]) ##", "head (L) #X is the position at which head is measured (L) #Conductance", "\"\"\" Transient General-Head Boundary Package First, we will create the GHB object, which", "(when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1])", "#dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value", "numpy package (aliased as np) can be used to quickly initialize the ibound", "bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100]", "LPF package to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%%", "hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list", "and as a starting point to compute the saturated thickness for cases of", "study area was assumed to be 1 ft/d, #which is consistent with model", "applied to all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge", "is used to specify which cells are active (value is positive), inactive (value", "genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy also has some pre-canned plotting capabilities", "contained in the binary head file * get_data() will return a three-dimensional head", "np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom of model is horizontal, approx. bedrock", "is head (L) #X is the position at which head is measured (L)", "heads from the MODFLOW binary output file, using the flopy.utils.binaryfile module. Included with", "binary utility that can be used to read the heads. The following statements", "dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly =", "set to 10 - use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. #", "Although this simulation is for steady flow, starting heads still need to be", "Mean Sea Level (MSL) in meters at closest NOAA station for stages #stageleft", "the study area was assumed to be 1 ft/d, #which is consistent with", "deposits was #assumed to be half the thickness of the model cell containing", "& ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start with freshwater at", "data output file. We cannot look at these heads with a text editor,", "= np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1, :, :] +", "= Ly/nrow #delv = (ztop - zbot) / nlay #botm = np.linspace(ztop, zbot,", "= np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to 10 - use data? calculate?", "matrix where hydraulic conductivities (hk = horiz, vk = vert) can be implemented", "range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol - 1,", "delr/2., delc/2., Ly - delc/2.) print('Levels: ', levels) print('Extent: ', extent) # Make", "headplot = plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot = plt.contour(head[0, :, :],", "#ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value (see drain for modification", "object, which is of the following type: flopy.modflow.ModflowGhb. The key to creating Flopy", "plotting doesn't seem to be able to allow averaging to reduce nrow and", "= zbot # Tutorial 1 model domain and grid definition #Lx = 1000.", "Lx - delr/2., Ly - delc/2., delc/2.) # headplot = plt.contour(head[0, :, :],", "# Use model_polygon to define active cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc)", "= True # first step steady state nstp = [nstp_default]*nper # number of", "so that Darcy's law can be expressed as #Q = -C(h1 - h0)", "better interpolate tidal changes, set to 0.5 hrs) perlen = [perlen_days]*nper # length", "= cell_spacing delc = cell_spacing delv = (dem_trans - zbot) / nlay botm", "are inactive genu.quick_plot(ibound) # plots boundary condition: 1 is above mean sea level", "with model simulations of similar coastal #discharge areas in other areas on Cape", "conditions (IBOUND), plot the grid, plot head contours, and plot vectors: \"\"\" fig", "dictionary with key values equal to the zero-based stress period number and values", "np.arange(1,10,1) extent = (delr/2., Lx - delr/2., Ly - delc/2., delc/2.) # headplot", "np.nan #levels = np.arange(1,10,1) extent = (delr/2., Lx - delr/2., Ly - delc/2.,", "vertical hydraulic conductivity of seabed deposits #(ft/d); #W is width of the model", "as shpu from cgw.utils import raster_utils as rastu # Assign name and create", "class. The following code shows how to use the modelmap class to plot", "list of [layer, row, column, stage, conductance]: Datums for 8447435, Chatham, Lydia Cove", "dem to model coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if", "# plots boundary condition: 1 is above mean sea level (msl), 0 is", "Using Mean Sea Level (MSL) in meters at closest NOAA station for stages", "model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell", "# Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc,", "n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set", "be a two-dimensional nested list of [layer, row, column, stage, conductance]: Datums for", "\"\"\" Time Stepping \"\"\" # Time step parameters total_length = 10 # days", "conditions for that stress period. For a GHB the values can be a", "area occupied by Salt Pond and Nauset #Marsh, it was assumed that there", "row 1 and column 1, and row 1 and column 201, can be", "steady[0] = True # first step steady state nstp = [nstp_default]*nper # number", "Boundary Package First, we will create the GHB object, which is of the", "stress period. For a GHB the values can be a two-dimensional nested list", "and hydrographs from the model results.: \"\"\" # headfile and budget file objects", "inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for everything less than msl ibound[:,np.isnan(dem_trans)]", "is under msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells &", "flopy.modflow.ModflowGhb. The key to creating Flopy transient boundary packages is recognizing that the", "used to quickly initialize the ibound array with values of 1, and then", "has some pre-canned plotting capabilities can can be accessed using the ModelMap class.", "#%% # Run the MODFLOW model success, buff = mf.run_model() #%% \"\"\" Post-Processing", "(DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) #", "and create a plot of simulated heads for layer 1: \"\"\" import flopy.utils.binaryfile", "by use of the plotting from the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf,", "\"\"\" Post-Processing the Results Once again, we can read heads from the MODFLOW", "shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active cells in the model ir,ic,_ =", "law can be expressed as #Q = -C(h1 - h0) #where C is", "= shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active cells in the model ir,ic,_", "# this drain will be applied to all stress periods drn = flopy.modflow.ModflowDrn(mf,", "is way higher resolution...can decimate it to save time decimate_by_ncells = 1 #", "stageright, condright]) ## Only 1 stress period for steady-state model #print('Adding ', len(bound_sp1),", "pre-canned plotting doesn't seem to be able to allow averaging to reduce nrow", "be half the thickness of the model cell containing the #boundary. # still", "coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active cells in the", "variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list # Can", "stage, conductance]: Datums for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make", "containing the seabed (ft); #L is length of the model cell containing the", "The following statements will read the binary head file and create a plot", "np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore cells are inactive", "= cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't seem to", "data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da =", "create head plots and hydrographs from the model results.: \"\"\" # headfile and", "value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to model coordinates with", "period number and values equal to the boundary conditions for that stress period.", "Need to fix grid to have fewer rows and columns #cs = modelmap.contour_array(head,", "1, 1, aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest', extent=(0, Lx, 0, Ly))", "cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0]", "from the model results.: \"\"\" # headfile and budget file objects already created", "flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value (see drain for modification based on", "was assumed that there were thick deposits of lowpermeability #material (<NAME>, U.S. Geological", "active cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot", "1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1]) levels", "markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig", "\"\"\" fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') im =", "vk = vert) can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything", "= fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx, 0,", "plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', #", "in a dictionary with key values equal to the zero-based stress period number", "Post-Processing the Results Now that we have successfully built and run our MODFLOW", "* (stageright - zbot) * delc # for ir in range(nrow): # bound_sp1.append([il,", "coastal #discharge areas in other areas on Cape Cod (Masterson and #others, 1998).", "#%% \"\"\" Time Stepping \"\"\" # Time step parameters total_length = 10 #", "qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png')", "zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5,", "binary output file, using the flopy.utils.binaryfile module. Included with the HeadFile object are", "hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf", "FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting", "= flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in meters at closest NOAA", "by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells]", "half the thickness of the model cell containing the #boundary. # still using", "shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx", "Again, commented out section using modelmap \"\"\" ## Flow right face and flow", "# start with freshwater at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start", "fixed-head cells (where ibound is negative), and as a starting point to compute", "is the area perpendicular to flow (L2) #h is head (L) #X is", "Add recharge condition # steady state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3,", "meters at closest NOAA station for stages #stageleft = mean_sea_level #stageright = mean_sea_level", "grid from a shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10.", "'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu from cgw.utils import feature_utils as", "the area occupied by Salt Pond and Nauset #Marsh, it was assumed that", "markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10,", "inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out", "# stress period time step divided by step time length (to better interpolate", "0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing", "# by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals =", "# start with water at sea level genu.quick_plot(strt) # plots starting condition bas", "stress period time step, hrs perlen_days = dt/24. # stress period time step,", "name and create modflow model object modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf", "# Tutorial 2 DIS object when transient conditions are implemented # dis =", "hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package First, we will create", "markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax", "Geological Survey, #oral commun., 2002) and the vertical hydraulic conductivity #was set to", "fix grid to have fewer rows and columns #cs = modelmap.contour_array(head, levels=levels) #quiver", "inactive (value is 0), or fixed head (value is negative). The numpy package", "# Pop out all of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs", "model grid cell spacing in meters # Define inputs for shp_to_grid function shp_to_grid_dict", "stress period nstp[0] = 1 #Tutorial 2 default time step parameters #nper =", "flow. ibound = np.ones((1, 201)) ibound[0, 0] = ibound[0, -1] = -1 \"\"\"", "flopy.utils.binaryfile module. Included with the HeadFile object are several methods that we will", "Define inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop", "the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc =", "# Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to", "divided by step time length (to better interpolate tidal changes, set to 0.5", "Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() #", "import flopy import numpy as np import sys,os import matplotlib.pyplot as plt #", "xarray data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know", "boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs", "active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start with freshwater at surface elevation strt[0,", "# #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\"", "= -1 # fixed head for everything less than msl ibound[:,np.isnan(dem_trans)] = 0", "BAS (basic) package # Added 5/28/19 \"\"\" Active cells and the like are", "all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition #", "#Tutorial 2 default time step parameters #nper = 3 #perlen = [1, 100,", "get hk values at each cell for changing conductance. # condleft = hk1[0,0,0]", "::iskip], -qy_avg[::iskip, 0, ::iskip], color='k', scale=5, headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%%", "flow (L2) #h is head (L) #X is the position at which head", "hrs perlen_days = dt/24. # stress period time step, days nper = int(total_length/perlen_days)", "the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\"", "first step as steady state steady = [False]*nper steady[0] = True # first", "of similar coastal #discharge areas in other areas on Cape Cod (Masterson and", "= r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid cell spacing", "file and create a plot of simulated heads for layer 1: \"\"\" import", "X, Y = np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip,", "np import sys,os import matplotlib.pyplot as plt # Location of BitBucket folder containing", "modelmap class to plot boundary conditions (IBOUND), plot the grid, plot head contours,", "plot of simulated heads for layer 1: \"\"\" import flopy.utils.binaryfile as bf from", "zbot) * delc # condright = hk1[0,0,0] * (stageright - zbot) * delc", "hk1[0,0,0] * (stageright - zbot) * delc # for ir in range(nrow): #", "and #others, 1998). In the area occupied by Salt Pond and Nauset #Marsh,", "can be referenced as [0,0], and [0,−1], respectively. Although this simulation is for", "model_polygon to define active cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells =", "= 0.5 * (frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :, 0]", "= 10 #ncol = 10 #delr = Lx/ncol #delc = Ly/nrow #delv =", "delc # for ir in range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft]) #", "(MSL) in meters at closest NOAA station for stages #stageleft = mean_sea_level #stageright", "10 #delr = Lx/ncol #delc = Ly/nrow #delv = (ztop - zbot) /", "= (delr/2., Lx - delr/2., delc/2., Ly - delc/2.) print('Levels: ', levels) print('Extent:", "vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package First, we will create the", "to define active cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic])", "interpolate tidal changes, set to 0.5 hrs) perlen = [perlen_days]*nper # length of", "Add PCG package to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write", "## Flow right face and flow front face already extracted ##%% ##Create the", "negative indexing so that row 1 and column 1, and row 1 and", "0.1 ft/d. The thickness of the seabed deposits was #assumed to be half", "1:ncol]) qx_avg[:, :, 0] = 0.5 * frf[:, :, 0] qy_avg = np.empty(fff.shape,", "1, 1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ##", "hydraulic conductivity of seabed deposits #(ft/d); #W is width of the model cell", "= shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle]", "= 10. # model grid cell spacing in meters # Define inputs for", "containing the seabed (ft); #and #M is thickness of seabed deposits (ft). #The", "model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if", "individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list #", "2002) and the vertical hydraulic conductivity #was set to 0.1 ft/d. The thickness", "Lx/ncol #delc = Ly/nrow #delv = (ztop - zbot) / nlay #botm =", "- h0)/(X1 - X0) #Where Q is the flow (L3/T) #K is the", "modflow model object modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir)", "= horiz, vk = vert) can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10.", "simple conductance land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero()", "= genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in", "as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM", "# bound_sp1.append([il, ir, ncol - 1, stageright, condright]) ## Only 1 stress period", "two-dimensional nested list of [layer, row, column, stage, conductance]: Datums for 8447435, Chatham,", "mean_sea_level = 0.843 # in meters at closest NOAA station #%% # Example", "value (see drain for modification based on Masterson, 2004) conductance = 1000. #", "0), or fixed head (value is negative). The numpy package (aliased as np)", "#nper = 3 #perlen = [1, 100, 100] #nstp = [1, 100, 100]", "vert) can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to", "ModelMap class. The following code shows how to use the modelmap class to", "matplotlib.pyplot as plt # Location of BitBucket folder containing cgw folder cgw_code_dir =", "10. # model grid cell spacing in meters # Define inputs for shp_to_grid", "1 # set first step as steady state steady = [False]*nper steady[0] =", "column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X", "= -50. #nlay = 1 #nrow = 10 #ncol = 10 #delr =", "# Know that dem is way higher resolution...can decimate it to save time", "of elapsed time since the previous point (need to change the first) perlen[0]", "#genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading DEM data for that", "# markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10))", "= flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS", "to use when cheq_griddev is implemented delr = cell_spacing delc = cell_spacing delv", "100] #steady = [True, False, False] #%% # Create the discretization (DIS) object", "we will create the GHB object, which is of the following type: flopy.modflow.ModflowGhb.", "stress period 1 # Using Mean Sea Level (MSL) in meters at closest", "exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in meters at", "= flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG package to the MODFLOW model", "number and values equal to the boundary conditions for that stress period. For", "starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19 - creates", "for stress period 1 # Using Mean Sea Level (MSL) in meters at", "X terms so that Darcy's law can be expressed as #Q = -C(h1", "creating Flopy transient boundary packages is recognizing that the boundary data is stored", "and the like are defined with the Basic package (BAS), which is required", "frf[:, :, 1:ncol]) qx_avg[:, :, 0] = 0.5 * frf[:, :, 0] qy_avg", "total_length = 10 # days dt = 6 # stress period time step,", "active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start", "Using these methods, we can create head plots and hydrographs from the model", "with color gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy also has some", "= -KA(h1 - h0)/(X1 - X0) #Where Q is the flow (L3/T) #K", "msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells are inactive genu.quick_plot(ibound) # plots boundary", "/ nlay #botm = np.linspace(ztop, zbot, nlay + 1) #%% \"\"\" Time Stepping", "model domain and grid definition #Lx = 1000. #Ly = 1000. #ztop =", "of the model cell containing the seabed (ft); #L is length of the", "Aug 29 15:47:36 2018 @author: akurnizk \"\"\" import flopy import numpy as np", "# condright = hk1[0,0,0] * (stageright - zbot) * delc # for ir", "period 1.') # #stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using", "cells (where ibound is negative), and as a starting point to compute the", "making it difficult to plot a large grid. The commented section below uses", "= [] stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add", "model cell containing the seabed (ft); #and #M is thickness of seabed deposits", "with freshwater at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with water", "levels=levels, extent=extent) # headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) #", "plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm =", "layer model nrow, ncol = cc[0].shape # to use when cheq_griddev is implemented", "with values of 1, and then set the ibound value for the first", "plot head contours, and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1,", "which is required for every MOD-FLOW model. It contains the ibound array, which", "frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%%", "grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the outputs into individual variables", "= np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip],", "flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model input files mf.write_input() #%% # Run", "by Salt Pond and Nauset #Marsh, it was assumed that there were thick", "the plots #Print statistics print('Head statistics') print(' min: ', head.min()) print(' max: ',", "= np.linspace(ztop, zbot, nlay + 1) #%% \"\"\" Time Stepping \"\"\" # Time", "equal to the zero-based stress period number and values equal to the boundary", "extracted ##%% ##Create the plot #f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal') #", "doesn't seem to be able to allow averaging to reduce nrow and ncol", "list # Can calculate cell centers (where heads are calculated), in different coordinates", "- creates matrix where hydraulic conductivities (hk = horiz, vk = vert) can", "np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)]", "1 # Using Mean Sea Level (MSL) in meters at closest NOAA station", "fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9)", "several methods that we will use here: * get_times() will return a list", "stress_period_data=stress_period_data) # using single conductance value (see drain for modification based on Masterson,", "and columns #cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\"", "outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform", "compute the saturated thickness for cases of unconfined flow. ibound = np.ones((1, 201))", "[m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%% # Add OC", "pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model input files mf.write_input() #%%", "np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] = 0.5 * (frf[:, :, 0:ncol-1] + frf[:,", "#botm = np.linspace(ztop, zbot, nlay + 1) #%% \"\"\" Time Stepping \"\"\" #", "8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress period", "we have successfully built and run our MODFLOW model, we can look at", "as a starting point to compute the saturated thickness for cases of unconfined", "area was assumed to be 1 ft/d, #which is consistent with model simulations", "no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to model coordinates", "['print head', 'print budget', 'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True)", "values at each cell for changing conductance. # condleft = hk1[0,0,0] * (stageleft", "mean_sea_level #bound_sp1 = [] #for il in range(nlay): # # Figure out looping", "- zbot) * delc # for ir in range(nrow): # bound_sp1.append([il, ir, 0,", "# using single conductance value (see drain for modification based on Masterson, 2004)", "Write the MODFLOW model input files mf.write_input() #%% # Run the MODFLOW model", "headfile and budget file objects already created # Setup contour parameters (levels already", "the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head", "is width of the model cell containing the seabed (ft); #L is length", "GHB the values can be a two-dimensional nested list of [layer, row, column,", "# to use when cheq_griddev is implemented delr = cell_spacing delc = cell_spacing", "(BAS), which is required for every MOD-FLOW model. It contains the ibound array,", "= {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same projection as model boundary shp", "= grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list # Can calculate cell", "(Masterson and #others, 1998). In the area occupied by Salt Pond and Nauset", "package to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\"", "#%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100", "\"\"\" Flopy also has some pre-canned plotting capabilities can can be accessed using", "model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading DEM data", "1 and column 1, and row 1 and column 201, can be referenced", "0 # far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head", "to reduce nrow and ncol on the plot, making it difficult to plot", "dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay, :,", "delc/2., delc/2.) # headplot = plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot =", "genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot", "meters at closest NOAA station #%% # Example of making a MODFLOW-like grid", "that can be used to read the heads. The following statements will read", "with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same projection", "use of the plotting from the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0)", "ncol - 1, stageright, condright]) ## Only 1 stress period for steady-state model", "delc/2.) # headplot = plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot = plt.contour(head[0,", "2 default time step parameters #nper = 3 #perlen = [1, 100, 100]", "3 #perlen = [1, 100, 100] #nstp = [1, 100, 100] #steady =", "value for the first and last columns to −1. The numpy package (and", "Tutorial 1, followed by use of the plotting from the Henry Problem. \"\"\"", "nrow, ncol = cc[0].shape # to use when cheq_griddev is implemented delr =", "dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan", "Added 5/28/19 \"\"\" Active cells and the like are defined with the Basic", "10 # days dt = 6 # stress period time step, hrs perlen_days", "aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() ## ## lc", "Lx - delr/2., delc/2., Ly - delc/2.) print('Levels: ', levels) print('Extent: ', extent)", "will use here: * get_times() will return a list of times contained in", "Masterson, 2004 # C = KWL/M where #C is hydraulic conductance of the", "cases of unconfined flow. ibound = np.ones((1, 201)) ibound[0, 0] = ibound[0, -1]", "rastu # Assign name and create modflow model object modelname = 'CheqModel1' work_dir", "nstp = [nstp_default]*nper # number of time steps in a stress period nstp[0]", "ibound is negative), and as a starting point to compute the saturated thickness", "Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress period 1", "grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list # Can calculate cell centers", "gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy also has some pre-canned plotting", "is an xarray data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname)", "1 layer model nrow, ncol = cc[0].shape # to use when cheq_griddev is", "the number of stress periods in the simulation nstp_default = dt/0.5 # stress", "can be expressed as #Q = -C(h1 - h0) #where C is the", "= dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip,", "days nper = int(total_length/perlen_days) # the number of stress periods in the simulation", "import numpy as np import sys,os import matplotlib.pyplot as plt # Location of", "approx. bedrock (check Masterson) nlay = 1 # 1 layer model nrow, ncol", "sys,os import matplotlib.pyplot as plt # Location of BitBucket folder containing cgw folder", "at these heads with a text editor, but flopy has a binary utility", "of the model cell containing the seabed (ft); #and #M is thickness of", "dt/0.5 # stress period time step divided by step time length (to better", "head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG package", "modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) #", "horiz, vk = vert) can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. #", "Only 1 stress period for steady-state model #print('Adding ', len(bound_sp1), 'GHBs for stress", "#oral commun., 2002) and the vertical hydraulic conductivity #was set to 0.1 ft/d.", "https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C = KWL/M where #C is hydraulic", "be able to allow averaging to reduce nrow and ncol on the plot,", "change the first) perlen[0] = 1 # set first step as steady state", "plt.show() #%% \"\"\" Post-Processing the Results Once again, we can read heads from", "elevations #%% \"\"\" Flopy also has some pre-canned plotting capabilities can can be", "fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, #", "elapsed time since the previous point (need to change the first) perlen[0] =", "np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to 10. # Add LPF package to", "plot, making it difficult to plot a large grid. The commented section below", "#ztop = 0. #zbot = -50. #nlay = 1 #nrow = 10 #ncol", "cell_spacing = 10. # model grid cell spacing in meters # Define inputs", "the results. MODFLOW writes the simulated heads to a binary data output file.", "nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] =", "= os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an", "active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} #", "creates matrix where hydraulic conductivities (hk = horiz, vk = vert) can be", "three-dimensional head array for the specified time * get_ts() will return a time", "#Marsh, it was assumed that there were thick deposits of lowpermeability #material (<NAME>,", "(ft); #and #M is thickness of seabed deposits (ft). #The vertical hydraulic conductivity", "#') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]')", "MOD-FLOW model. It contains the ibound array, which is used to specify which", "read the binary head file and create a plot of simulated heads for", "are implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop,", "= flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition # steady state, units in", "1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx, 0, Ly)) y,", "class from Tutorial 1, followed by use of the plotting from the Henry", "state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf #%%", "the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans,", "how to use the modelmap class to plot boundary conditions (IBOUND), plot the", "np.float) hk1[:,:,:]=10. # everything set to 10 - use data? calculate? vka1 =", "ax = fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest', extent=(0,", "(to better interpolate tidal changes, set to 0.5 hrs) perlen = [perlen_days]*nper #", "[1, 100, 100] #nstp = [1, 100, 100] #steady = [True, False, False]", "# headfile and budget file objects already created # Setup contour parameters (levels", "time since the previous point (need to change the first) perlen[0] = 1", "of lowpermeability #material (<NAME>, U.S. Geological Survey, #oral commun., 2002) and the vertical", "conductance of the seabed (ft2/d); #K is vertical hydraulic conductivity of seabed deposits", "every MOD-FLOW model. It contains the ibound array, which is used to specify", "return a three-dimensional head array for the specified time * get_ts() will return", "= modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing SEAWAT) ucnobj", "the plotting from the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm =", "= dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform", "levels = np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf =", "dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that dem is way higher", "Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress period 1 #", "#ncol = 10 #delr = Lx/ncol #delc = Ly/nrow #delv = (ztop -", "= modelmap.plot_grid() # Need to fix grid to have fewer rows and columns", "np) can be used to quickly initialize the ibound array with values of", "delr/2., Ly - delc/2., delc/2.) # headplot = plt.contour(head[0, :, :], levels=levels, extent=extent)", "0.5 * (frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:, :, 0] =", "modelmap \"\"\" ## Flow right face and flow front face already extracted ##%%", "delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay,", "#%% # added 3/8/19 - creates matrix where hydraulic conductivities (hk = horiz,", "ibound = np.ones((1, 201)) ibound[0, 0] = ibound[0, -1] = -1 \"\"\" ibound", "il in range(nlay): # # Figure out looping through hk1 array to get", "1, and then set the ibound value for the first and last columns", "based on Masterson, 2004) conductance = 1000. # (modify 1000 to actual conductance)", "elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with water at sea level genu.quick_plot(strt)", "and then set the ibound value for the first and last columns to", "or fixed head (value is negative). The numpy package (aliased as np) can", "be expressed as #Q = -C(h1 - h0) #where C is the conductance", "[1, 100, 100] #steady = [True, False, False] #%% # Create the discretization", "# Tutorial 1 model domain and grid definition #Lx = 1000. #Ly =", "= cc[0].shape # to use when cheq_griddev is implemented delr = cell_spacing delc", "(see drain for modification based on Masterson, 2004) conductance = 1000. # (modify", "stress_period_data=lrcec) #%% # Add recharge condition # steady state, units in [m/day]? rch", "get_ts() will return a time series array [ntimes, headval] for the specified cell", "= modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data", "dis.get_node_coordinates() X, Y = np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip],", "cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't seem to be", "states that #Q = -KA(h1 - h0)/(X1 - X0) #Where Q is the", "active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column", "inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom", "ibound array with values of 1, and then set the ibound value for", "negative). The numpy package (aliased as np) can be used to quickly initialize", "The pre-canned plotting doesn't seem to be able to allow averaging to reduce", "will return a three-dimensional head array for the specified time * get_ts() will", ":]) qy_avg[0, :, :] = 0.5 * fff[0, :, :] # Make the", "flow, starting heads still need to be specified. They are used as the", "the model cell containing the seabed (ft); #L is length of the model", "- use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to", "General-Head Boundary Package First, we will create the GHB object, which is of", "that we have successfully built and run our MODFLOW model, we can look", "ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax =", "space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]')", "the plot, making it difficult to plot a large grid. The commented section", "for stages #stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1 = [] #for il", "plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads')", "at the results. MODFLOW writes the simulated heads to a binary data output", "added 3/8/19 - creates matrix where hydraulic conductivities (hk = horiz, vk =", "Stepping \"\"\" # Time step parameters total_length = 10 # days dt =", "#Ly = 1000. #ztop = 0. #zbot = -50. #nlay = 1 #nrow", "budget file objects already created # Setup contour parameters (levels already set) extent", "(K) of the seabed #deposits in most of the study area was assumed", "initialize the ibound array with values of 1, and then set the ibound", "= vert) can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set", "object when transient conditions are implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol,", "#%% # Add OC package to the MODFLOW model spd = {(0, 0):", "number of time steps in a stress period nstp[0] = 1 #Tutorial 2", "= 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu from cgw.utils import feature_utils", "\"\"\" # Make list for stress period 1 # Using Mean Sea Level", "top=dem_trans, botm=botm) # Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol,", "# nan cells are inactive genu.quick_plot(ibound) # plots boundary condition: 1 is above", "matrix is the amount # of elapsed time since the previous point (need", "the following type: flopy.modflow.ModflowGhb. The key to creating Flopy transient boundary packages is", "required for every MOD-FLOW model. It contains the ibound array, which is used", "for the specified cell Using these methods, we can create head plots and", "ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for everything less than msl ibound[:,np.isnan(dem_trans)] =", "A and X terms so that Darcy's law can be expressed as #Q", "\"\"\" Created on Wed Aug 29 15:47:36 2018 @author: akurnizk \"\"\" import flopy", "perlen = [perlen_days]*nper # length of a stress period; each item in the", "plots boundary condition: 1 is above mean sea level (msl), 0 is msl,", "modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver =", "Add OC package to the MODFLOW model spd = {(0, 0): ['print head',", "is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C =", "model spd = {(0, 0): ['print head', 'print budget', 'save head', 'save budget']}", "#f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0)", "this drain will be applied to all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec)", "a plot of simulated heads for layer 1: \"\"\" import flopy.utils.binaryfile as bf", "cell containing the seabed (ft); #and #M is thickness of seabed deposits (ft).", "frf[:, :, 0] qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 *", "create a plot of simulated heads for layer 1: \"\"\" import flopy.utils.binaryfile as", "cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column #')", "* (fff[0:nlay-1, :, :] + fff[1:nlay, :, :]) qy_avg[0, :, :] = 0.5", "Example of loading DEM data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental", "headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as", "in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of loading DEM", "-1] = -1 \"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0", "#plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times", "thickness of seabed deposits (ft). #The vertical hydraulic conductivity (K) of the seabed", "the MODFLOW model success, buff = mf.run_model() #%% \"\"\" Post-Processing the Results Now", "= cell_spacing delv = (dem_trans - zbot) / nlay botm = zbot #", "# number of time steps in a stress period nstp[0] = 1 #Tutorial", "above mean sea level (msl), 0 is msl, -1 is under msl. strt", "* get_data() will return a three-dimensional head array for the specified time *", "= 1 #Tutorial 2 default time step parameters #nper = 3 #perlen =", "# 1 layer model nrow, ncol = cc[0].shape # to use when cheq_griddev", "centers (where heads are calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use", "numpy as np import sys,os import matplotlib.pyplot as plt # Location of BitBucket", "= 10 #delr = Lx/ncol #delc = Ly/nrow #delv = (ztop - zbot)", "of [layer, row, column, stage, conductance]: Datums for 8447435, Chatham, Lydia Cove MA", "#others, 1998). In the area occupied by Salt Pond and Nauset #Marsh, it", "* get_times() will return a list of times contained in the binary head", "looping through hk1 array to get hk values at each cell for changing", "cc[0].shape # to use when cheq_griddev is implemented delr = cell_spacing delc =", "to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to model coordinates with linear", "'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add PCG package to", "read the heads. The following statements will read the binary head file and", "model nrow, ncol = cc[0].shape # to use when cheq_griddev is implemented delr", "# if bottom of model is horizontal, approx. bedrock (check Masterson) nlay =", "referenced as [0,0], and [0,−1], respectively. Although this simulation is for steady flow,", "model success, buff = mf.run_model() #%% \"\"\" Post-Processing the Results Now that we", "model, we can look at the results. MODFLOW writes the simulated heads to", "#mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From", "nstp=nstp, steady=steady) #%% # Variables for the BAS (basic) package # Added 5/28/19", "ir in range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol", "#K is vertical hydraulic conductivity of seabed deposits #(ft/d); #W is width of", "= 1 # 1 layer model nrow, ncol = cc[0].shape # to use", "heads still need to be specified. They are used as the head for", "already created # Setup contour parameters (levels already set) extent = (delr/2., Lx", "item in the matrix is the amount # of elapsed time since the", "cell for changing conductance. # condleft = hk1[0,0,0] * (stageleft - zbot) *", "decimate it to save time decimate_by_ncells = 1 # by every n cells", "ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] =", "of the seabed (ft2/d); #K is vertical hydraulic conductivity of seabed deposits #(ft/d);", "the #boundary. # still using simple conductance land_cells = active_cells & ~np.isnan(dem_trans) &", "fixed head for everything less than msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells", "Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid()", "10 - use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set", "Run the MODFLOW model success, buff = mf.run_model() #%% \"\"\" Post-Processing the Results", "dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that dem is way higher resolution...can decimate", "#cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff,", "from Tutorial 1, followed by use of the plotting from the Henry Problem.", "success, buff = mf.run_model() #%% \"\"\" Post-Processing the Results Now that we have", "respectively. Although this simulation is for steady flow, starting heads still need to", "10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest',", "SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" #", "DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 #", "0 # nan cells are inactive genu.quick_plot(ibound) # plots boundary condition: 1 is", "package to the MODFLOW model spd = {(0, 0): ['print head', 'print budget',", "set) extent = (delr/2., Lx - delr/2., delc/2., Ly - delc/2.) print('Levels: ',", "stored in a dictionary with key values equal to the zero-based stress period", "# Run the MODFLOW model success, buff = mf.run_model() #%% \"\"\" Post-Processing the", "= np.ones((1, 201)) ibound[0, 0] = ibound[0, -1] = -1 \"\"\" ibound =", "mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 #", "plots elevations #%% \"\"\" Flopy also has some pre-canned plotting capabilities can can", "to use the modelmap class to plot boundary conditions (IBOUND), plot the grid,", "in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon to define active cells", "= modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10,", "will be applied to all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% #", "#assumed to be half the thickness of the model cell containing the #boundary.", "for steady-state model #print('Adding ', len(bound_sp1), 'GHBs for stress period 1.') # #stress_period_data", "cell_spacing delv = (dem_trans - zbot) / nlay botm = zbot # Tutorial", "* get_ts() will return a time series array [ntimes, headval] for the specified", "Package First, we will create the GHB object, which is of the following", "at closest NOAA station #%% # Example of making a MODFLOW-like grid from", "= 1000. # (modify 1000 to actual conductance) bound_sp1 = [] stress_period_data =", "= [nstp_default]*nper # number of time steps in a stress period nstp[0] =", "is msl, -1 is under msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights", "head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list =", "steady state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=1.4e-3) # from https://pubs.usgs.gov/wsp/2447/report.pdf", "of seabed deposits #(ft/d); #W is width of the model cell containing the", "= 0.5 * fff[0, :, :] # Make the plot fig = plt.figure(figsize=(10,", "dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan", "head file * get_data() will return a three-dimensional head array for the specified", "plot boundary conditions (IBOUND), plot the grid, plot head contours, and plot vectors:", "#c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%% Example of", "delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for", "# if dem in same projection as model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict)", "nan cells are inactive genu.quick_plot(ibound) # plots boundary condition: 1 is above mean", "ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average", "2004 # C = KWL/M where #C is hydraulic conductance of the seabed", "MODFLOW model spd = {(0, 0): ['print head', 'print budget', 'save head', 'save", "rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx = np.amax(dem_X)-np.amin(dem_X) Ly", "= flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package First, we", "ibound=ibound, strt=strt) #%% # added 3/8/19 - creates matrix where hydraulic conductivities (hk", "stress period; each item in the matrix is the amount # of elapsed", "stress period number and values equal to the boundary conditions for that stress", "#(ft/d); #W is width of the model cell containing the seabed (ft); #L", "layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to fix grid to", "-*- coding: utf-8 -*- \"\"\" Created on Wed Aug 29 15:47:36 2018 @author:", "condright = hk1[0,0,0] * (stageright - zbot) * delc # for ir in", "head.std()) \"\"\" Again, commented out section using modelmap \"\"\" ## Flow right face", "boundary conditions for that stress period. For a GHB the values can be", "plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results Once again, we can read heads", "steady flow, starting heads still need to be specified. They are used as", "#nstp = [1, 100, 100] #steady = [True, False, False] #%% # Create", "# stress period time step, days nper = int(total_length/perlen_days) # the number of", "of loading DEM data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part", "shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of", "{0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value (see drain", "first and last columns to −1. The numpy package (and Python, in general)", "budget', 'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%% # Add", "= plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot = plt.contour(head[0, :, :], extent=extent)", "alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf,", "that there were thick deposits of lowpermeability #material (<NAME>, U.S. Geological Survey, #oral", "previous point (need to change the first) perlen[0] = 1 # set first", "seabed (ft); #L is length of the model cell containing the seabed (ft);", "stress period for steady-state model #print('Adding ', len(bound_sp1), 'GHBs for stress period 1.')", "head for fixed-head cells (where ibound is negative), and as a starting point", "np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT", "# -*- coding: utf-8 -*- \"\"\" Created on Wed Aug 29 15:47:36 2018", "specified time * get_ts() will return a time series array [ntimes, headval] for", "objects already created # Setup contour parameters (levels already set) extent = (delr/2.,", "exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in meters at closest NOAA station #%%", "#lc = modelmap.plot_grid() # Need to fix grid to have fewer rows and", ":], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head)", "array with values of 1, and then set the ibound value for the", "MODFLOW model success, buff = mf.run_model() #%% \"\"\" Post-Processing the Results Now that", "row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal')", "(delr/2., Lx - delr/2., delc/2., Ly - delc/2.) print('Levels: ', levels) print('Extent: ',", "#%% # Variables for the BAS (basic) package # Added 5/28/19 \"\"\" Active", "can be a two-dimensional nested list of [layer, row, column, stage, conductance]: Datums", "heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color gradient genu.quick_plot(dem_trans)", "in meters at closest NOAA station #%% # Example of making a MODFLOW-like", "cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data", "# everything set to 10. # Add LPF package to the MODFLOW model", "transient boundary packages is recognizing that the boundary data is stored in a", "plotting capabilities can can be accessed using the ModelMap class. The following code", "for the first and last columns to −1. The numpy package (and Python,", "#delv = (ztop - zbot) / nlay #botm = np.linspace(ztop, zbot, nlay +", "to plot boundary conditions (IBOUND), plot the grid, plot head contours, and plot", "conductance land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec", "head for everything less than msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells are", "#for il in range(nlay): # # Figure out looping through hk1 array to", "still need to be specified. They are used as the head for fixed-head", "ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights", "modification based on Masterson, 2004) conductance = 1000. # (modify 1000 to actual", "import general_utils as genu from cgw.utils import feature_utils as shpu from cgw.utils import", "nlay = 1 # 1 layer model nrow, ncol = cc[0].shape # to", "zbot # Tutorial 1 model domain and grid definition #Lx = 1000. #Ly", "10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE',", "tidal changes, set to 0.5 hrs) perlen = [perlen_days]*nper # length of a", "were thick deposits of lowpermeability #material (<NAME>, U.S. Geological Survey, #oral commun., 2002)", "dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1", "boundary conditions (IBOUND), plot the grid, plot head contours, and plot vectors: \"\"\"", ":, :] # Make the plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1,", "cells are inactive genu.quick_plot(ibound) # plots boundary condition: 1 is above mean sea", "flopy import numpy as np import sys,os import matplotlib.pyplot as plt # Location", "The following code shows how to use the modelmap class to plot boundary", "#L is length of the model cell containing the seabed (ft); #and #M", "quickly initialize the ibound array with values of 1, and then set the", "to all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition", "{'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the outputs into individual", "the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make", "need to be specified. They are used as the head for fixed-head cells", "able to allow averaging to reduce nrow and ncol on the plot, making", "= hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1) extent = (delr/2., Lx -", "to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model", "Tutorial 1 model domain and grid definition #Lx = 1000. #Ly = 1000.", "# extent=(0, Lx, 0, Ly)) y, x, z = dis.get_node_coordinates() X, Y =", "simulation is for steady flow, starting heads still need to be specified. They", "- h0) #where C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson,", "general_utils as genu from cgw.utils import feature_utils as shpu from cgw.utils import raster_utils", "#ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y", "-1 is under msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells", "closest NOAA station #%% # Example of making a MODFLOW-like grid from a", "the MODFLOW model spd = {(0, 0): ['print head', 'print budget', 'save head',", "plt # Location of BitBucket folder containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir)", "as plt # Location of BitBucket folder containing cgw folder cgw_code_dir = 'E:\\python'", "statements will read the binary head file and create a plot of simulated", "MODFLOW binary output file, using the flopy.utils.binaryfile module. Included with the HeadFile object", "positive), inactive (value is 0), or fixed head (value is negative). The numpy", "array [ntimes, headval] for the specified cell Using these methods, we can create", "of BitBucket folder containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import", "seem to be able to allow averaging to reduce nrow and ncol on", "it was assumed that there were thick deposits of lowpermeability #material (<NAME>, U.S.", "plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') hds", "object are several methods that we will use here: * get_times() will return", "mean sea level (msl), 0 is msl, -1 is under msl. strt =", "# fixed head for everything less than msl ibound[:,np.isnan(dem_trans)] = 0 # nan", "period. For a GHB the values can be a two-dimensional nested list of", "folder containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as", "'new_xy':cc_proj} # if dem in same projection as model boundary shp dem_trans =", "as np import sys,os import matplotlib.pyplot as plt # Location of BitBucket folder", "perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for the BAS (basic) package # Added", "pre-canned plotting capabilities can can be accessed using the ModelMap class. The following", "flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS object", "number of stress periods in the simulation nstp_default = dt/0.5 # stress period", "# still using simple conductance land_cells = active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows,", "botm = zbot # Tutorial 1 model domain and grid definition #Lx =", "Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to model", "Tutorial 2 DIS object when transient conditions are implemented # dis = flopy.modflow.ModflowDis(mf,", "Created on Wed Aug 29 15:47:36 2018 @author: akurnizk \"\"\" import flopy import", "vertical hydraulic conductivity (K) of the seabed #deposits in most of the study", "= {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied to all stress periods drn", "of the plotting from the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm", "a list of times contained in the binary head file * get_data() will", "is thickness of seabed deposits (ft). #The vertical hydraulic conductivity (K) of the", "commented section below uses the modelmap class from Tutorial 1, followed by use", "= 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0, ::iskip], color='k',", "= int(total_length/perlen_days) # the number of stress periods in the simulation nstp_default =", "array, which is used to specify which cells are active (value is positive),", "can be used to read the heads. The following statements will read the", "heads with color gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy also has", "#qm = modelmap.plot_bc('GHB', alpha=0.5) #cs = modelmap.contour_array(head, levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11)", "os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an xarray", "0 is msl, -1 is under msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32)", "# #stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance", "29 15:47:36 2018 @author: akurnizk \"\"\" import flopy import numpy as np import", "plotting from the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound()", "Y = np.meshgrid(x, y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0,", "to the MODFLOW model lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient", "1, and row 1 and column 201, can be referenced as [0,0], and", "following code shows how to use the modelmap class to plot boundary conditions", ":, 1:] = 0.5 * (frf[:, :, 0:ncol-1] + frf[:, :, 1:ncol]) qx_avg[:,", "flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition # steady state, units in [m/day]?", "length of a stress period; each item in the matrix is the amount", "= np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights = dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells &", "marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\"", "packages is recognizing that the boundary data is stored in a dictionary with", "to read the heads. The following statements will read the binary head file", "extent = (delr/2., Lx - delr/2., delc/2., Ly - delc/2.) print('Levels: ', levels)", "cells are inactive ibound[0,dem_trans<mean_sea_level] = -1 # fixed head for everything less than", "# plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color", "head=head) # #mfc='black' #plt.plot(lw=0, marker='o', markersize=8, # markeredgewidth=0.5, # markeredgecolor='black', markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png')", "#%% # Add recharge condition # steady state, units in [m/day]? rch =", "(modify 1000 to actual conductance) bound_sp1 = [] stress_period_data = {0: bound_sp1} ghb", "the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model input", "- delr/2., Ly - delc/2., delc/2.) # headplot = plt.contour(head[0, :, :], levels=levels,", "active (value is positive), inactive (value is 0), or fixed head (value is", "= active_dem_heights # start with freshwater at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level", "range(nlay): # # Figure out looping through hk1 array to get hk values", "dt/24. # stress period time step, days nper = int(total_length/perlen_days) # the number", "# Create the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr,", "#Print statistics print('Head statistics') print(' min: ', head.min()) print(' max: ', head.max()) print('", "K, A and X terms so that Darcy's law can be expressed as", "parameters total_length = 10 # days dt = 6 # stress period time", "results. MODFLOW writes the simulated heads to a binary data output file. We", "Location of BitBucket folder containing cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils", "length of the model cell containing the seabed (ft); #and #M is thickness", "= 0.843 # in meters at closest NOAA station #%% # Example of", "@author: akurnizk \"\"\" import flopy import numpy as np import sys,os import matplotlib.pyplot", "station for stages #stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1 = [] #for", "Q is the flow (L3/T) #K is the hydraulic conductivity (L/T) #A is", "#h is head (L) #X is the position at which head is measured", "trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem in same projection as model boundary", "statistics print('Head statistics') print(' min: ', head.min()) print(' max: ', head.max()) print(' std:", "level genu.quick_plot(strt) # plots starting condition bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% #", "', head.max()) print(' std: ', head.std()) \"\"\" Again, commented out section using modelmap", "flopy has a binary utility that can be used to read the heads.", "drain will be applied to all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%%", "grid definition #Lx = 1000. #Ly = 1000. #ztop = 0. #zbot =", "(ztop - zbot) / nlay #botm = np.linspace(ztop, zbot, nlay + 1) #%%", "to model coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} # if dem", "nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables for the BAS (basic) package #", "bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19 - creates matrix where", "= np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to 10. # Add LPF package", "higher resolution...can decimate it to save time decimate_by_ncells = 1 # by every", ":] + fff[1:nlay, :, :]) qy_avg[0, :, :] = 0.5 * fff[0, :,", ":], levels=levels, extent=extent) # headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly') plt.colorbar(headplot)", "conductivity (L/T) #A is the area perpendicular to flow (L2) #h is head", "flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19 - creates matrix where hydraulic conductivities", "the seabed #deposits in most of the study area was assumed to be", "the binary head file * get_data() will return a three-dimensional head array for", "the amount # of elapsed time since the previous point (need to change", "<NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') im", "# (modify 1000 to actual conductance) bound_sp1 = [] stress_period_data = {0: bound_sp1}", "= KWL/M where #C is hydraulic conductance of the seabed (ft2/d); #K is", "= flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to fix", "the seabed (ft); #and #M is thickness of seabed deposits (ft). #The vertical", "import matplotlib.pyplot as plt # Location of BitBucket folder containing cgw folder cgw_code_dir", "plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1)", "(and Python, in general) uses zero-based indexing and supports negative indexing so that", "#%% \"\"\" Transient General-Head Boundary Package First, we will create the GHB object,", "#%% # Write the MODFLOW model input files mf.write_input() #%% # Run the", "days dt = 6 # stress period time step, hrs perlen_days = dt/24.", "sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu from cgw.utils import feature_utils as shpu", "list for stress period 1 # Using Mean Sea Level (MSL) in meters", "the model cell containing the seabed (ft); #and #M is thickness of seabed", "concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell centers qx_avg = np.empty(frf.shape,", "which is used to specify which cells are active (value is positive), inactive", "perpendicular to flow (L2) #h is head (L) #X is the position at", "successfully built and run our MODFLOW model, we can look at the results.", "cgw folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu from", "~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start with freshwater at surface", "ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore cells", "2018 @author: akurnizk \"\"\" import flopy import numpy as np import sys,os import", "genu.np.nan # Transform dem to model coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear',", "#%% # Add PCG package to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%%", "boundary data is stored in a dictionary with key values equal to the", "for fixed-head cells (where ibound is negative), and as a starting point to", "head plots and hydrographs from the model results.: \"\"\" # headfile and budget", "1998). In the area occupied by Salt Pond and Nauset #Marsh, it was", "occupied by Salt Pond and Nauset #Marsh, it was assumed that there were", "and plot vectors: \"\"\" fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal')", "Average flows to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :, 1:] =", "values can be a two-dimensional nested list of [layer, row, column, stage, conductance]:", "the previous point (need to change the first) perlen[0] = 1 # set", "be referenced as [0,0], and [0,−1], respectively. Although this simulation is for steady", "binary data output file. We cannot look at these heads with a text", "on the plot, making it difficult to plot a large grid. The commented", "code shows how to use the modelmap class to plot boundary conditions (IBOUND),", "transform list # Can calculate cell centers (where heads are calculated), in different", "# bound_sp1.append([il, ir, 0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol - 1, stageright,", "= plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm", "and [0,−1], respectively. Although this simulation is for steady flow, starting heads still", "modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when", "ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:,", "model cell containing the #boundary. # still using simple conductance land_cells = active_cells", "ibound array, which is used to specify which cells are active (value is", "to be specified. They are used as the head for fixed-head cells (where", "terms so that Darcy's law can be expressed as #Q = -C(h1 -", "# Assign name and create modflow model object modelname = 'CheqModel1' work_dir =", "fixed head (value is negative). The numpy package (aliased as np) can be", "std: ', head.std()) \"\"\" Again, commented out section using modelmap \"\"\" ## Flow", "that stress period. For a GHB the values can be a two-dimensional nested", "levels=levels) #plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black'", "that row 1 and column 1, and row 1 and column 201, can", "is horizontal, approx. bedrock (check Masterson) nlay = 1 # 1 layer model", "#zbot = -50. #nlay = 1 #nrow = 10 #ncol = 10 #delr", "period; each item in the matrix is the amount # of elapsed time", "dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore cells are inactive ibound[0,dem_trans<mean_sea_level] = -1", "(hk = horiz, vk = vert) can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float)", "bf.HeadFile(modelname+'.hds') times = hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb", "is consistent with model simulations of similar coastal #discharge areas in other areas", "#plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads with color gradient genu.quick_plot(dem_trans) # plots elevations", "# Make list for stress period 1 # Using Mean Sea Level (MSL)", "Salt Pond and Nauset #Marsh, it was assumed that there were thick deposits", "Survey, #oral commun., 2002) and the vertical hydraulic conductivity #was set to 0.1", "define active cells in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\"", "columns to −1. The numpy package (and Python, in general) uses zero-based indexing", "for modification based on Masterson, 2004) conductance = 1000. # (modify 1000 to", "can be accessed using the ModelMap class. The following code shows how to", "# # Figure out looping through hk1 array to get hk values at", "(levels already set) extent = (delr/2., Lx - delr/2., delc/2., Ly - delc/2.)", "there were thick deposits of lowpermeability #material (<NAME>, U.S. Geological Survey, #oral commun.,", "Ly - delc/2.) print('Levels: ', levels) print('Extent: ', extent) # Make the plots", "first) perlen[0] = 1 # set first step as steady state steady =", "model is horizontal, approx. bedrock (check Masterson) nlay = 1 # 1 layer", "lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain will be applied to all stress periods", "data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10. # everything set to 10. #", "#deposits in most of the study area was assumed to be 1 ft/d,", "y) iskip = 3 ax.quiver(X[::iskip, ::iskip], Y[::iskip, ::iskip], qx_avg[::iskip, 0, ::iskip], -qy_avg[::iskip, 0,", "markerfacecolor=mfc, zorder=9) #plt.savefig('CheqModel2-{}.png') \"\"\" From <NAME> \"\"\" fig = plt.figure(figsize=(10, 10)) ax =", "# Using Mean Sea Level (MSL) in meters at closest NOAA station for", "for everything less than msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells are inactive", "conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C = KWL/M where", "following statements will read the binary head file and create a plot of", "as the head for fixed-head cells (where ibound is negative), and as a", "cell_spacing delc = cell_spacing delv = (dem_trans - zbot) / nlay botm =", "#Q = -KA(h1 - h0)/(X1 - X0) #Where Q is the flow (L3/T)", "to the boundary conditions for that stress period. For a GHB the values", "conductance value (see drain for modification based on Masterson, 2004) conductance = 1000.", "period time step, hrs perlen_days = dt/24. # stress period time step, days", "# first step steady state nstp = [nstp_default]*nper # number of time steps", "Once again, we can read heads from the MODFLOW binary output file, using", "as rastu # Assign name and create modflow model object modelname = 'CheqModel1'", "numpy package (and Python, in general) uses zero-based indexing and supports negative indexing", "modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname,", "each cell for changing conductance. # condleft = hk1[0,0,0] * (stageleft - zbot)", "\"\"\" # Load data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times =", "= 1 # set first step as steady state steady = [False]*nper steady[0]", "= bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff =", "* delc # for ir in range(nrow): # bound_sp1.append([il, ir, 0, stageleft, condleft])", "# added 3/8/19 - creates matrix where hydraulic conductivities (hk = horiz, vk", "totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't seem to be able to allow", "it difficult to plot a large grid. The commented section below uses the", "1, aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest', extent=(0, Lx, 0, Ly)) ax.set_title('Simulated", "= genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int))", "Know that dem is way higher resolution...can decimate it to save time decimate_by_ncells", "kstpkper_list = cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT", "at each cell for changing conductance. # condleft = hk1[0,0,0] * (stageleft -", "indexing and supports negative indexing so that row 1 and column 1, and", "times = hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb =", "\"\"\" ## Flow right face and flow front face already extracted ##%% ##Create", "model pcg = flopy.modflow.ModflowPcg(mf) #%% # Write the MODFLOW model input files mf.write_input()", "Results Once again, we can read heads from the MODFLOW binary output file,", "be 1 ft/d, #which is consistent with model simulations of similar coastal #discharge", "changes, set to 0.5 hrs) perlen = [perlen_days]*nper # length of a stress", ":, :] = 0.5 * fff[0, :, :] # Make the plot fig", "##Create the plot #f = plt.figure() #plt.subplot(1, 1, 1, aspect='equal') # # #modelmap", "definition #Lx = 1000. #Ly = 1000. #ztop = 0. #zbot = -50.", "delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% # Variables", "10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0,", "and the vertical hydraulic conductivity #was set to 0.1 ft/d. The thickness of", "1, followed by use of the plotting from the Henry Problem. \"\"\" #modelmap", "a stress period nstp[0] = 1 #Tutorial 2 default time step parameters #nper", "h0) #where C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004", "(where heads are calculated), in different coordinates cc,cc_proj,cc_ll = shpu.nodes_to_cc([X_nodes,Y_nodes],grid_transform) # Use model_polygon", "law states that #Q = -KA(h1 - h0)/(X1 - X0) #Where Q is", "# Add OC package to the MODFLOW model spd = {(0, 0): ['print", "# C = KWL/M where #C is hydraulic conductance of the seabed (ft2/d);", "= modelmap.plot_ibound() ## ## lc = modelmap.plot_grid() #qm = modelmap.plot_bc('GHB', alpha=0.5) #cs =", "msl, -1 is under msl. strt = np.ones((nlay, nrow, ncol), dtype=np.float32) active_dem_heights =", "from a shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. #", "zero-based indexing and supports negative indexing so that row 1 and column 1,", "flow (L3/T) #K is the hydraulic conductivity (L/T) #A is the area perpendicular", "modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need to fix grid to have fewer rows", "# Make the plots #Print statistics print('Head statistics') print(' min: ', head.min()) print('", "grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list # Can calculate cell centers (where", "the K, A and X terms so that Darcy's law can be expressed", "conditions are implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #", "(need to change the first) perlen[0] = 1 # set first step as", "to the zero-based stress period number and values equal to the boundary conditions", "seabed deposits #(ft/d); #W is width of the model cell containing the seabed", "default time step parameters #nper = 3 #perlen = [1, 100, 100] #nstp", "created # Setup contour parameters (levels already set) extent = (delr/2., Lx -", "qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay, :, :])", "#ax[0].set_ylabel('row #') #c1=ax[1].pcolormesh(cc[0],cc[1],active_cells.astype(int)) # in model coordinates #genu.plt.colorbar(c1,ax=ax[1],orientation='horizontal') #ax[1].set_xlabel('X [m]') #ax[1].set_ylabel('Y [m]') #%%", "in range(nlay): # # Figure out looping through hk1 array to get hk", "assumed that there were thick deposits of lowpermeability #material (<NAME>, U.S. Geological Survey,", "#%% Example of loading DEM data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') #", "dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model inputs Lx =", "deposits of lowpermeability #material (<NAME>, U.S. Geological Survey, #oral commun., 2002) and the", "be applied to all stress periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add", "head file and create a plot of simulated heads for layer 1: \"\"\"", "100] #nstp = [1, 100, 100] #steady = [True, False, False] #%% #", "hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels = np.arange(1,10,1) extent", "all of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle]", "column 1, and row 1 and column 201, can be referenced as [0,0],", "model boundary shp dem_trans = rastu.subsection_griddata(**trans_dict) dem_trans[dem_trans<-1000] = genu.np.nan genu.quick_plot(dem_trans) #%% DEM model", "ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%% #", "plots and hydrographs from the model results.: \"\"\" # headfile and budget file", "unconfined flow. ibound = np.ones((1, 201)) ibound[0, 0] = ibound[0, -1] = -1", "condright]) ## Only 1 stress period for steady-state model #print('Adding ', len(bound_sp1), 'GHBs", ":, :], levels=levels, extent=extent) # headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx') plt.ylabel('Ly')", "for cases of unconfined flow. ibound = np.ones((1, 201)) ibound[0, 0] = ibound[0,", "by step time length (to better interpolate tidal changes, set to 0.5 hrs)", "zbot = -100 # if bottom of model is horizontal, approx. bedrock (check", "discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm)", "object dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial", "#%% \"\"\" The pre-canned plotting doesn't seem to be able to allow averaging", "Pop out all of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform", "C = KWL/M where #C is hydraulic conductance of the seabed (ft2/d); #K", "## Only 1 stress period for steady-state model #print('Adding ', len(bound_sp1), 'GHBs for", "\"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far offshore", "r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid cell spacing in", "the like are defined with the Basic package (BAS), which is required for", "everything set to 10 - use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float) vka1[:,:,:]=10.", "1000. #Ly = 1000. #ztop = 0. #zbot = -50. #nlay = 1", "plt.contour(head[0, :, :], levels=levels, extent=extent) # headplot = plt.contour(head[0, :, :], extent=extent) plt.xlabel('Lx')", "stress period time step divided by step time length (to better interpolate tidal", "It contains the ibound array, which is used to specify which cells are", "hydraulic conductivity (K) of the seabed #deposits in most of the study area", "= r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level =", "already set) extent = (delr/2., Lx - delr/2., delc/2., Ly - delc/2.) print('Levels:", "aspect='equal') #ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx, 0, Ly)) y, x, z", "is vertical hydraulic conductivity of seabed deposits #(ft/d); #W is width of the", "(value is negative). The numpy package (aliased as np) can be used to", "= mf.run_model() #%% \"\"\" Post-Processing the Results Now that we have successfully built", "flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object", "condleft = hk1[0,0,0] * (stageleft - zbot) * delc # condright = hk1[0,0,0]", "\"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row", "inline=1, fontsize=10, fmt='%1.1f', zorder=11) #quiver = modelmap.plot_discharge(frf, fff, head=head) # #mfc='black' #plt.plot(lw=0, marker='o',", "= np.amax(dem_X)-np.amin(dem_X) Ly = np.amax(dem_Y)-np.amin(dem_Y) zbot = -100 # if bottom of model", "width of the model cell containing the seabed (ft); #L is length of", "step parameters #nper = 3 #perlen = [1, 100, 100] #nstp = [1,", "[ntimes, headval] for the specified cell Using these methods, we can create head", "1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:])", "(L) #X is the position at which head is measured (L) #Conductance combines", "is for steady flow, starting heads still need to be specified. They are", "in most of the study area was assumed to be 1 ft/d, #which", "the thickness of the model cell containing the #boundary. # still using simple", "nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen, nstp=nstp, steady=steady) #%%", "is the flow (L3/T) #K is the hydraulic conductivity (L/T) #A is the", "package # Added 5/28/19 \"\"\" Active cells and the like are defined with", "= -1 \"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 #", ":] # Make the plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1,", "#dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]]", "flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in meters at closest NOAA station", "# model grid cell spacing in meters # Define inputs for shp_to_grid function", "flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt = flopy.seawat.Seawat(modelname, exe_name='swtv4') print(swt.namefile) mean_sea_level = 0.843 # in meters", "print(' max: ', head.max()) print(' std: ', head.std()) \"\"\" Again, commented out section", "to actual conductance) bound_sp1 = [] stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf,", "# everything set to 10 - use data? calculate? vka1 = np.ones((nlay,nrow,ncol), np.float)", "contains the ibound array, which is used to specify which cells are active", "= dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that dem is way", "when transient conditions are implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr,", "\"\"\" Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column", "can be implemented hk1 = np.ones((nlay,nrow,ncol), np.float) hk1[:,:,:]=10. # everything set to 10", "plt.ylabel('Ly') plt.colorbar(headplot) # plots heads as contours #plt.colorbar.set_label('heads') plt.savefig('CheqModel1a.png') genu.quick_plot(head) # plots heads", "the ibound array, which is used to specify which cells are active (value", "file objects already created # Setup contour parameters (levels already set) extent =", "print(' min: ', head.min()) print(' max: ', head.max()) print(' std: ', head.std()) \"\"\"", "dem is way higher resolution...can decimate it to save time decimate_by_ncells = 1", "cheq_griddev is implemented delr = cell_spacing delc = cell_spacing delv = (dem_trans -", "delc # condright = hk1[0,0,0] * (stageright - zbot) * delc # for", "data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid cell", "input files mf.write_input() #%% # Run the MODFLOW model success, buff = mf.run_model()", "\"\"\" Post-Processing the Results Now that we have successfully built and run our", "# Add PCG package to the MODFLOW model pcg = flopy.modflow.ModflowPcg(mf) #%% #", "grid cell spacing in meters # Define inputs for shp_to_grid function shp_to_grid_dict =", "stages #stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1 = [] #for il in", "import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1]) head[head<-100] = np.nan #levels", "#%% # Add drain condition #Darcy's law states that #Q = -KA(h1 -", "in general) uses zero-based indexing and supports negative indexing so that row 1", "that dem is way higher resolution...can decimate it to save time decimate_by_ncells =", "= ucnobj.get_times() concentration = ucnobj.get_data(totim=times[-1]) \"\"\" # Average flows to cell centers qx_avg", "domain and grid definition #Lx = 1000. #Ly = 1000. #ztop = 0.", "= (dem_trans - zbot) / nlay botm = zbot # Tutorial 1 model", "a stress period; each item in the matrix is the amount # of", "row, column, stage, conductance]: Datums for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\"", "Flopy transient boundary packages is recognizing that the boundary data is stored in", "/ nlay botm = zbot # Tutorial 1 model domain and grid definition", "shpu from cgw.utils import raster_utils as rastu # Assign name and create modflow", "time step divided by step time length (to better interpolate tidal changes, set", "1 #Tutorial 2 default time step parameters #nper = 3 #perlen = [1,", "plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:, 0, :],", "of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] #", "# https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from Masterson, 2004 # C = KWL/M where #C is", "= flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) # using single conductance value (see drain for modification based", "last columns to −1. The numpy package (and Python, in general) uses zero-based", "the modelmap class from Tutorial 1, followed by use of the plotting from", "& ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this", "= {(0, 0): ['print head', 'print budget', 'save head', 'save budget']} oc =", "these heads with a text editor, but flopy has a binary utility that", "that we will use here: * get_times() will return a list of times", "as steady state steady = [False]*nper steady[0] = True # first step steady", "totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't", "dem_trans[active_cells & ~np.isnan(dem_trans)] strt[0, active_cells & ~np.isnan(dem_trans)] = active_dem_heights # start with freshwater", "= mean_sea_level #bound_sp1 = [] #for il in range(nlay): # # Figure out", "get_times() will return a list of times contained in the binary head file", "data (when implementing SEAWAT) ucnobj = bf.UcnFile('MT3D001.UCN', model=swt) times = ucnobj.get_times() concentration =", "# Can calculate cell centers (where heads are calculated), in different coordinates cc,cc_proj,cc_ll", "NOAA station for stages #stageleft = mean_sea_level #stageright = mean_sea_level #bound_sp1 = []", "the matrix is the amount # of elapsed time since the previous point", "= genu.np.nan # Transform dem to model coordinates with linear interpolation trans_dict =", "is implemented delr = cell_spacing delc = cell_spacing delv = (dem_trans - zbot)", "shapefile data_dir = r'E:\\ArcGIS' shp_fname = os.path.join(data_dir,'Chequesset_Model_Area_UTM.shp') cell_spacing = 10. # model grid", "loading DEM data for that area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/", "zbot) * delc # for ir in range(nrow): # bound_sp1.append([il, ir, 0, stageleft,", "#delc = Ly/nrow #delv = (ztop - zbot) / nlay #botm = np.linspace(ztop,", "Python, in general) uses zero-based indexing and supports negative indexing so that row", "row 1 and column 201, can be referenced as [0,0], and [0,−1], respectively.", "used to read the heads. The following statements will read the binary head", "module. Included with the HeadFile object are several methods that we will use", "flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's law states that #Q =", "a GHB the values can be a two-dimensional nested list of [layer, row,", "methods, we can create head plots and hydrographs from the model results.: \"\"\"", "headwidth=3, headlength=2, headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results Once again,", "= active_cells & ~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])}", "#levels = np.arange(1,10,1) extent = (delr/2., Lx - delr/2., Ly - delc/2., delc/2.)", "for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA \"\"\" # Make list for stress", "model results.: \"\"\" # headfile and budget file objects already created # Setup", "first step steady state nstp = [nstp_default]*nper # number of time steps in", "active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells \"\"\" #fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) #", "# Add drain condition #Darcy's law states that #Q = -KA(h1 - h0)/(X1", "#fig,ax = genu.plt.subplots(1,2) #genu.quick_plot(active_cells.astype(int),ax=ax[0]) # in row, column space #ax[0].set_xlabel('column #') #ax[0].set_ylabel('row #')", "Assign name and create modflow model object modelname = 'CheqModel1' work_dir = r'E:\\Herring'", "= [False]*nper steady[0] = True # first step steady state nstp = [nstp_default]*nper", "# Setup contour parameters (levels already set) extent = (delr/2., Lx - delr/2.,", "model object modelname = 'CheqModel1' work_dir = r'E:\\Herring' mf = flopy.modflow.Modflow(modelname, exe_name='mf2005',model_ws=work_dir) swt", "0): ['print head', 'print budget', 'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd,", "is of the following type: flopy.modflow.ModflowGhb. The key to creating Flopy transient boundary", "starting point to compute the saturated thickness for cases of unconfined flow. ibound", "into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list", "dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that dem is", "genu.quick_plot(head) # plots heads with color gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\"", "zbot) / nlay botm = zbot # Tutorial 1 model domain and grid", "time * get_ts() will return a time series array [ntimes, headval] for the", "mf.run_model() #%% \"\"\" Post-Processing the Results Now that we have successfully built and", "the BAS (basic) package # Added 5/28/19 \"\"\" Active cells and the like", "#dem_vals = dem_vals[::decimate_by_ncells,::decimate_by_ncells] # Set no-data value to nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan #", "#%% \"\"\" Post-Processing the Results Now that we have successfully built and run", "hk1 array to get hk values at each cell for changing conductance. #", "[nstp_default]*nper # number of time steps in a stress period nstp[0] = 1", "the boundary data is stored in a dictionary with key values equal to", "as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal') hds = bf.HeadFile(os.path.join(work_dir,modelname+'.hds')) head = hds.get_data(totim=hds.get_times()[-1])", "= rastu.read_griddata(dem_fname) # Know that dem is way higher resolution...can decimate it to", "\"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc = modelmap.plot_grid() # Need", "use here: * get_times() will return a list of times contained in the", "201)) ibound[0, 0] = ibound[0, -1] = -1 \"\"\" ibound = np.ones((nlay, nrow,", "cell containing the seabed (ft); #L is length of the model cell containing", "headaxislength=2, width=0.0025) plt.savefig('CheqModel1b.png') plt.show() #%% \"\"\" Post-Processing the Results Once again, we can", "delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow,", "nstp_default = dt/0.5 # stress period time step divided by step time length", "if bottom of model is horizontal, approx. bedrock (check Masterson) nlay = 1", "output file. We cannot look at these heads with a text editor, but", "bound_sp1 = [] stress_period_data = {0: bound_sp1} ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) #%% #", "in the model ir,ic,_ = shpu.gridpts_in_shp(model_polygon,cc) active_cells = genu.define_mask(cc,[ir,ic]) \"\"\" Plot active cells", "shpu.shp_to_grid(**shp_to_grid_dict) # Pop out all of the outputs into individual variables [X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] =", "Transform dem to model coordinates with linear interpolation trans_dict = {'orig_xy':[dem_X,dem_Y],'orig_val':dem_vals,'active_method':'linear', 'new_xy':cc_proj} #", "from the Henry Problem. \"\"\" #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound() #lc", "min: ', head.min()) print(' max: ', head.max()) print(' std: ', head.std()) \"\"\" Again,", "periods drn = flopy.modflow.ModflowDrn(mf, stress_period_data=lrcec) #%% # Add recharge condition # steady state,", "can create head plots and hydrographs from the model results.: \"\"\" # headfile", "', head.std()) \"\"\" Again, commented out section using modelmap \"\"\" ## Flow right", "color gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy also has some pre-canned", "= flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=dem_trans, botm=botm) # Tutorial 1 DIS", "fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, aspect='equal') hds = bf.HeadFile(modelname+'.hds') times", "First, we will create the GHB object, which is of the following type:", "= cbb.get_kstpkper() frf = cbb.get_data(text='FLOW RIGHT FACE', totim=times[-1])[0] fff = cbb.get_data(text='FLOW FRONT FACE',", "is the position at which head is measured (L) #Conductance combines the K,", "time series array [ntimes, headval] for the specified cell Using these methods, we", "fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest', extent=(0, Lx, 0,", "* (stageleft - zbot) * delc # condright = hk1[0,0,0] * (stageright -", "nan dem_vals[dem_vals==dem_da.nodatavals[0]] = genu.np.nan # Transform dem to model coordinates with linear interpolation", "They are used as the head for fixed-head cells (where ibound is negative),", "= hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc') kstpkper_list = cbb.get_kstpkper()", "import raster_utils as rastu # Assign name and create modflow model object modelname", "a two-dimensional nested list of [layer, row, column, stage, conductance]: Datums for 8447435,", "= hds.get_times() head = hds.get_data(totim=times[-1]) levels = np.linspace(0, 10, 11) cbb = bf.CellBudgetFile(modelname+'.cbc')", "is negative), and as a starting point to compute the saturated thickness for", "= flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], # nper=nper, perlen=perlen,", "# dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:], #", "= flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) #%% # added 3/8/19 - creates matrix where hydraulic", "(ft); #L is length of the model cell containing the seabed (ft); #and", "\"\"\" # Average flows to cell centers qx_avg = np.empty(frf.shape, dtype=frf.dtype) qx_avg[:, :,", "accessed using the ModelMap class. The following code shows how to use the", "#and #M is thickness of seabed deposits (ft). #The vertical hydraulic conductivity (K)", "#cs = modelmap.contour_array(head, levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load", "= (delr/2., Lx - delr/2., Ly - delc/2., delc/2.) # headplot = plt.contour(head[0,", "stress_period_data=stress_period_data) #%% # Add drain condition #Darcy's law states that #Q = -KA(h1", "to change the first) perlen[0] = 1 # set first step as steady", "#ax.imshow(concentration[:, 0, :], interpolation='nearest', # extent=(0, Lx, 0, Ly)) y, x, z =", "#top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object when transient conditions are implemented #", "array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) # Know that dem", "lpf = flopy.modflow.ModflowLpf(mf, hk=hk1, vka=vka1, ipakcb=53) #%% \"\"\" Transient General-Head Boundary Package First,", "where hydraulic conductivities (hk = horiz, vk = vert) can be implemented hk1", "#nlay = 1 #nrow = 10 #ncol = 10 #delr = Lx/ncol #delc", "model simulations of similar coastal #discharge areas in other areas on Cape Cod", "= 0 # nan cells are inactive genu.quick_plot(ibound) # plots boundary condition: 1", "model input files mf.write_input() #%% # Run the MODFLOW model success, buff =", "= 0.5 * (fff[0:nlay-1, :, :] + fff[1:nlay, :, :]) qy_avg[0, :, :]", "nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial 2 DIS object when", "head', 'print budget', 'save head', 'save budget']} oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) #%%", "# Time step parameters total_length = 10 # days dt = 6 #", "heads for layer 1: \"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable", "Flopy also has some pre-canned plotting capabilities can can be accessed using the", "the ibound value for the first and last columns to −1. The numpy", "FACE', totim=times[-1])[0] #%% \"\"\" The pre-canned plotting doesn't seem to be able to", "the HeadFile object are several methods that we will use here: * get_times()", "from cgw.utils import general_utils as genu from cgw.utils import feature_utils as shpu from", "qy_avg = np.empty(fff.shape, dtype=fff.dtype) qy_avg[1:, :, :] = 0.5 * (fff[0:nlay-1, :, :]", "interpolation='nearest', # extent=(0, Lx, 0, Ly)) y, x, z = dis.get_node_coordinates() X, Y", "heads to a binary data output file. We cannot look at these heads", "in the simulation nstp_default = dt/0.5 # stress period time step divided by", "# Define inputs for shp_to_grid function shp_to_grid_dict = {'shp':shp_fname,'cell_spacing':cell_spacing} grid_outputs = shpu.shp_to_grid(**shp_to_grid_dict) #", "to plot a large grid. The commented section below uses the modelmap class", "to a binary data output file. We cannot look at these heads with", "#plt.subplot(1, 1, 1, aspect='equal') # # #modelmap = flopy.plot.ModelMap(model=mf, layer=0) #qm = modelmap.plot_ibound()", "= [1, 100, 100] #steady = [True, False, False] #%% # Create the", "is required for every MOD-FLOW model. It contains the ibound array, which is", "#M is thickness of seabed deposits (ft). #The vertical hydraulic conductivity (K) of", "(IBOUND), plot the grid, plot head contours, and plot vectors: \"\"\" fig =", "= fig.add_subplot(1, 1, 1, aspect='equal') im = ax.imshow(head[:, 0, :], interpolation='nearest', extent=(0, Lx,", "Tutorial 1 DIS object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals,", "0] = ibound[0, -1] = -1 \"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32)", "hydrographs from the model results.: \"\"\" # headfile and budget file objects already", "capabilities can can be accessed using the ModelMap class. The following code shows", "ibound[0, 0] = ibound[0, -1] = -1 \"\"\" ibound = np.ones((nlay, nrow, ncol),", "start with freshwater at surface elevation strt[0, dem_trans<mean_sea_level] = mean_sea_level # start with", "= hk1[0,0,0] * (stageleft - zbot) * delc # condright = hk1[0,0,0] *", "file, using the flopy.utils.binaryfile module. Included with the HeadFile object are several methods", "of the model cell containing the #boundary. # still using simple conductance land_cells", "negative), and as a starting point to compute the saturated thickness for cases", "thickness of the model cell containing the #boundary. # still using simple conductance", "for layer 1: \"\"\" import flopy.utils.binaryfile as bf from mpl_toolkits.axes_grid1 import make_axes_locatable plt.subplot(1,1,1,aspect='equal')", "shows how to use the modelmap class to plot boundary conditions (IBOUND), plot", "= 0. #zbot = -50. #nlay = 1 #nrow = 10 #ncol =", "plots heads with color gradient genu.quick_plot(dem_trans) # plots elevations #%% \"\"\" Flopy also", "[True, False, False] #%% # Create the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf,", "but flopy has a binary utility that can be used to read the", "nstp[0] = 1 #Tutorial 2 default time step parameters #nper = 3 #perlen", "~np.isnan(dem_trans) & (dem_trans>mean_sea_level) landrows, landcols = land_cells.nonzero() lrcec = {0:np.column_stack([np.zeros_like(landrows),landrows,landcols,dem_trans[land_cells],conductance*np.ones_like(landrows)])} # this drain", "with a text editor, but flopy has a binary utility that can be", "0, stageleft, condleft]) # bound_sp1.append([il, ir, ncol - 1, stageright, condright]) ## Only", "vertical hydraulic conductivity #was set to 0.1 ft/d. The thickness of the seabed", "folder cgw_code_dir = 'E:\\python' sys.path.insert(0,cgw_code_dir) from cgw.utils import general_utils as genu from cgw.utils", "so that row 1 and column 1, and row 1 and column 201,", "file. We cannot look at these heads with a text editor, but flopy", "area dem_fname = os.path.join(data_dir,'Cheq10mx10m_UTM.tif') # Experimental part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da", "are used as the head for fixed-head cells (where ibound is negative), and", "False, False] #%% # Create the discretization (DIS) object dis = flopy.modflow.ModflowDis(mf, nlay,", "Example of making a MODFLOW-like grid from a shapefile data_dir = r'E:\\ArcGIS' shp_fname", "1 # by every n cells #dem_X = dem_X[::decimate_by_ncells,::decimate_by_ncells] #dem_Y = dem_Y[::decimate_by_ncells,::decimate_by_ncells] #dem_vals", "-1 \"\"\" ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) ibound[:,~active_cells] = 0 # far", "-C(h1 - h0) #where C is the conductance (L2/T) # https://water.usgs.gov/nrp/gwsoftware/modflow2000/MFDOC/index.html?drn.htm # from", "look at these heads with a text editor, but flopy has a binary", "True # first step steady state nstp = [nstp_default]*nper # number of time", "transient conditions are implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc,", "less than msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells are inactive genu.quick_plot(ibound) #", "period for steady-state model #print('Adding ', len(bound_sp1), 'GHBs for stress period 1.') #", "implemented # dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, # top=ztop, botm=botm[1:],", "than msl ibound[:,np.isnan(dem_trans)] = 0 # nan cells are inactive genu.quick_plot(ibound) # plots", "part \\/ dem_X,dem_Y,dem_da = rastu.load_geotif(dem_fname) # da is an xarray data array dem_vals", "= [1, 100, 100] #nstp = [1, 100, 100] #steady = [True, False,", "[layer, row, column, stage, conductance]: Datums for 8447435, Chatham, Lydia Cove MA https://tidesandcurrents.noaa.gov/datums.html?units=1&epoch=0&id=8447435&name=Chatham%2C+Lydia+Cove&state=MA", "for stress period 1.') # #stress_period_data = {0: bound_sp1} #ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data)", "(ft). #The vertical hydraulic conductivity (K) of the seabed #deposits in most of", "an xarray data array dem_vals = dem_da.values.squeeze() #dem_X, dem_Y, dem_vals = rastu.read_griddata(dem_fname) #", "mf.write_input() #%% # Run the MODFLOW model success, buff = mf.run_model() #%% \"\"\"", "The numpy package (and Python, in general) uses zero-based indexing and supports negative", "object #dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, #top=dem_vals, botm=botm[1:]) # Tutorial", "# Add recharge condition # steady state, units in [m/day]? rch = flopy.modflow.ModflowRch(mf,", "levels=levels) #quiver = modelmap.plot_discharge(frf, fff, head=head) #plt.savefig('CheqModel1b.png') \"\"\" # Load data (when implementing", "we will use here: * get_times() will return a list of times contained", "[X_nodes,Y_nodes],model_polygon,[out_proj,[xshift,yshift],min_angle] = grid_outputs grid_transform = [out_proj,[xshift,yshift],min_angle] # make transform list # Can calculate", "these methods, we can create head plots and hydrographs from the model results.:" ]
[ "BOLD, title, sticky_status, RESET, BOLD, author, mod_status ), i ) b.l_say( 'Subreddit: %s", "\"\"\" def parselink(link): meta_data_link = link + '.json' tables = urllib.urlopen(meta_data_link) data =", "input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle multiple links for word in m:", "True def reddit(l, b, i): \"\"\" !d Alias for .parsereddit !a <link> !r", "else: b.l_say('Usage: .parsereddit <link>', i, 0) return True def reddit(l, b, i): \"\"\"", "Treat input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle", "\"\"\" Oracle 2.0 IRC Bot reddit.py plugin module http://toofifty.me/oracle \"\"\" import urllib, json", "= data['title'] author = data['author'] subreddit = data['subreddit'] score = data['score'] comments =", "def parselink(link): meta_data_link = link + '.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data']", "2.0 IRC Bot reddit.py plugin module http://toofifty.me/oracle \"\"\" import urllib, json from format", "b, i): \"\"\" !d Parse a Reddit link into it's information !a <link>", "as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle multiple links", "format import BOLD, RESET def _init(bot): print '\\t%s loaded' % __name__ def parsereddit(l,", "'' sticky_status = ' [sticky]' if data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s", "= link + '.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title']", "# Treat input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] #", "input.set_user(bot.get_user(n)) input.args = [] # Handle multiple links for word in m: if", "link in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i,", "%s%s%s%s by %s%s%s' % ( BOLD, title, sticky_status, RESET, BOLD, author, mod_status ),", "% ( BOLD, title, sticky_status, RESET, BOLD, author, mod_status ), i ) b.l_say(", "[] # Handle multiple links for word in m: if '.reddit.com/' in word:", "data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' % ( BOLD, title,", "if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0) return True", "<link>', i, 0) return True def reddit(l, b, i): \"\"\" !d Alias for", "meta_data_link = link + '.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title =", "sticky_status = ' [sticky]' if data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s by", "Comments: %s' \\ % (subreddit, score, comments), i ) if i.args > 0:", "into it's information !a <link> !r user \"\"\" def parselink(link): meta_data_link = link", "bot.new_input(n, c, m) # Treat input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args", "args): n, c, m = args if '.reddit.com/' in ' '.join(m): input =", "module http://toofifty.me/oracle \"\"\" import urllib, json from format import BOLD, RESET def _init(bot):", "Reddit link into it's information !a <link> !r user \"\"\" def parselink(link): meta_data_link", "if data['distinguished'] == 'moderator' else '' sticky_status = ' [sticky]' if data['stickied'] else", "args if '.reddit.com/' in ' '.join(m): input = bot.new_input(n, c, m) # Treat", ".parsereddit !a <link> !r user \"\"\" return parsereddit(l, b, i) def _chat(bot, args):", "( BOLD, title, sticky_status, RESET, BOLD, author, mod_status ), i ) b.l_say( 'Subreddit:", "!d Parse a Reddit link into it's information !a <link> !r user \"\"\"", "% __name__ def parsereddit(l, b, i): \"\"\" !d Parse a Reddit link into", "for .parsereddit !a <link> !r user \"\"\" return parsereddit(l, b, i) def _chat(bot,", "data['num_comments'] mod_status = ' [M]' if data['distinguished'] == 'moderator' else '' sticky_status =", "i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0) return True def reddit(l, b,", "BOLD, author, mod_status ), i ) b.l_say( 'Subreddit: %s | Score: %s |", "loaded' % __name__ def parsereddit(l, b, i): \"\"\" !d Parse a Reddit link", "data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author'] subreddit = data['subreddit'] score", "parselink(link): meta_data_link = link + '.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title", "\"\"\" !d Parse a Reddit link into it's information !a <link> !r user", "in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0)", "\"\"\" return parsereddit(l, b, i) def _chat(bot, args): n, c, m = args", "= args if '.reddit.com/' in ' '.join(m): input = bot.new_input(n, c, m) #", "b, i): \"\"\" !d Alias for .parsereddit !a <link> !r user \"\"\" return", "reddit(l, b, i): \"\"\" !d Alias for .parsereddit !a <link> !r user \"\"\"", "<link> !r user \"\"\" def parselink(link): meta_data_link = link + '.json' tables =", "n, c, m = args if '.reddit.com/' in ' '.join(m): input = bot.new_input(n,", "urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author'] subreddit = data['subreddit']", "import urllib, json from format import BOLD, RESET def _init(bot): print '\\t%s loaded'", "user \"\"\" def parselink(link): meta_data_link = link + '.json' tables = urllib.urlopen(meta_data_link) data", "'' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' % ( BOLD, title, sticky_status, RESET,", "reddit.py plugin module http://toofifty.me/oracle \"\"\" import urllib, json from format import BOLD, RESET", "sticky_status, RESET, BOLD, author, mod_status ), i ) b.l_say( 'Subreddit: %s | Score:", "command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle multiple links for word", "__name__ def parsereddit(l, b, i): \"\"\" !d Parse a Reddit link into it's", "by %s%s%s' % ( BOLD, title, sticky_status, RESET, BOLD, author, mod_status ), i", "return parsereddit(l, b, i) def _chat(bot, args): n, c, m = args if", "i): \"\"\" !d Parse a Reddit link into it's information !a <link> !r", ".parsereddit <link>', i, 0) return True def reddit(l, b, i): \"\"\" !d Alias", "[sticky]' if data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' % (", "'moderator' else '' sticky_status = ' [sticky]' if data['stickied'] else '' b.l_say( 'Reddit", "user \"\"\" return parsereddit(l, b, i) def _chat(bot, args): n, c, m =", "Parse a Reddit link into it's information !a <link> !r user \"\"\" def", "' [sticky]' if data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' %", "else '' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' % ( BOLD, title, sticky_status,", "> 0: for link in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage:", "in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0) return True def reddit(l,", "Handle multiple links for word in m: if '.reddit.com/' in word: input.args.append(word) bot.plugins.process_command(bot,", "RESET, BOLD, author, mod_status ), i ) b.l_say( 'Subreddit: %s | Score: %s", "mod_status ), i ) b.l_say( 'Subreddit: %s | Score: %s | Comments: %s'", "else '' sticky_status = ' [sticky]' if data['stickied'] else '' b.l_say( 'Reddit post:", "http://toofifty.me/oracle \"\"\" import urllib, json from format import BOLD, RESET def _init(bot): print", "BOLD, RESET def _init(bot): print '\\t%s loaded' % __name__ def parsereddit(l, b, i):", "= data['num_comments'] mod_status = ' [M]' if data['distinguished'] == 'moderator' else '' sticky_status", "), i ) b.l_say( 'Subreddit: %s | Score: %s | Comments: %s' \\", "author = data['author'] subreddit = data['subreddit'] score = data['score'] comments = data['num_comments'] mod_status", "data['distinguished'] == 'moderator' else '' sticky_status = ' [sticky]' if data['stickied'] else ''", "%s' \\ % (subreddit, score, comments), i ) if i.args > 0: for", "if i.args > 0: for link in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower())", "json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author'] subreddit = data['subreddit'] score = data['score']", "b, i) def _chat(bot, args): n, c, m = args if '.reddit.com/' in", "m) # Treat input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = []", "from format import BOLD, RESET def _init(bot): print '\\t%s loaded' % __name__ def", "def _init(bot): print '\\t%s loaded' % __name__ def parsereddit(l, b, i): \"\"\" !d", "parsereddit(l, b, i): \"\"\" !d Parse a Reddit link into it's information !a", "\"\"\" import urllib, json from format import BOLD, RESET def _init(bot): print '\\t%s", "%s | Score: %s | Comments: %s' \\ % (subreddit, score, comments), i", "in ' '.join(m): input = bot.new_input(n, c, m) # Treat input as a", "input = bot.new_input(n, c, m) # Treat input as a command. input.set_command('parsereddit') input.set_level(1)", "a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle multiple links for", "Oracle 2.0 IRC Bot reddit.py plugin module http://toofifty.me/oracle \"\"\" import urllib, json from", "'\\t%s loaded' % __name__ def parsereddit(l, b, i): \"\"\" !d Parse a Reddit", "title, sticky_status, RESET, BOLD, author, mod_status ), i ) b.l_say( 'Subreddit: %s |", "data['subreddit'] score = data['score'] comments = data['num_comments'] mod_status = ' [M]' if data['distinguished']", "i) def _chat(bot, args): n, c, m = args if '.reddit.com/' in '", "% (subreddit, score, comments), i ) if i.args > 0: for link in", "'.join(m): input = bot.new_input(n, c, m) # Treat input as a command. input.set_command('parsereddit')", "!r user \"\"\" def parselink(link): meta_data_link = link + '.json' tables = urllib.urlopen(meta_data_link)", "= bot.new_input(n, c, m) # Treat input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n))", "i ) if i.args > 0: for link in i.args: if '.reddit.com/' in", ") b.l_say( 'Subreddit: %s | Score: %s | Comments: %s' \\ % (subreddit,", "parsereddit(l, b, i) def _chat(bot, args): n, c, m = args if '.reddit.com/'", "= data['subreddit'] score = data['score'] comments = data['num_comments'] mod_status = ' [M]' if", "\"\"\" !d Alias for .parsereddit !a <link> !r user \"\"\" return parsereddit(l, b,", "def _chat(bot, args): n, c, m = args if '.reddit.com/' in ' '.join(m):", "(subreddit, score, comments), i ) if i.args > 0: for link in i.args:", "' '.join(m): input = bot.new_input(n, c, m) # Treat input as a command.", "input.args = [] # Handle multiple links for word in m: if '.reddit.com/'", "= json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author'] subreddit = data['subreddit'] score =", "subreddit = data['subreddit'] score = data['score'] comments = data['num_comments'] mod_status = ' [M]'", "author, mod_status ), i ) b.l_say( 'Subreddit: %s | Score: %s | Comments:", "Bot reddit.py plugin module http://toofifty.me/oracle \"\"\" import urllib, json from format import BOLD,", "i): \"\"\" !d Alias for .parsereddit !a <link> !r user \"\"\" return parsereddit(l,", "Score: %s | Comments: %s' \\ % (subreddit, score, comments), i ) if", "'.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0) return True def", "b.l_say('Usage: .parsereddit <link>', i, 0) return True def reddit(l, b, i): \"\"\" !d", "print '\\t%s loaded' % __name__ def parsereddit(l, b, i): \"\"\" !d Parse a", "def parsereddit(l, b, i): \"\"\" !d Parse a Reddit link into it's information", "| Comments: %s' \\ % (subreddit, score, comments), i ) if i.args >", "_chat(bot, args): n, c, m = args if '.reddit.com/' in ' '.join(m): input", "data['title'] author = data['author'] subreddit = data['subreddit'] score = data['score'] comments = data['num_comments']", "it's information !a <link> !r user \"\"\" def parselink(link): meta_data_link = link +", "%s | Comments: %s' \\ % (subreddit, score, comments), i ) if i.args", "0: for link in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit", "i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0) return", "post: %s%s%s%s by %s%s%s' % ( BOLD, title, sticky_status, RESET, BOLD, author, mod_status", "json from format import BOLD, RESET def _init(bot): print '\\t%s loaded' % __name__", "if '.reddit.com/' in ' '.join(m): input = bot.new_input(n, c, m) # Treat input", "data['author'] subreddit = data['subreddit'] score = data['score'] comments = data['num_comments'] mod_status = '", "c, m) # Treat input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args =", "= [] # Handle multiple links for word in m: if '.reddit.com/' in", "= data['author'] subreddit = data['subreddit'] score = data['score'] comments = data['num_comments'] mod_status =", "\\ % (subreddit, score, comments), i ) if i.args > 0: for link", "RESET def _init(bot): print '\\t%s loaded' % __name__ def parsereddit(l, b, i): \"\"\"", "link into it's information !a <link> !r user \"\"\" def parselink(link): meta_data_link =", "' [M]' if data['distinguished'] == 'moderator' else '' sticky_status = ' [sticky]' if", "= data['score'] comments = data['num_comments'] mod_status = ' [M]' if data['distinguished'] == 'moderator'", "comments = data['num_comments'] mod_status = ' [M]' if data['distinguished'] == 'moderator' else ''", "urllib, json from format import BOLD, RESET def _init(bot): print '\\t%s loaded' %", "# Handle multiple links for word in m: if '.reddit.com/' in word: input.args.append(word)", "0) return True def reddit(l, b, i): \"\"\" !d Alias for .parsereddit !a", "%s%s%s' % ( BOLD, title, sticky_status, RESET, BOLD, author, mod_status ), i )", "input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle multiple links for word in", "tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author'] subreddit", ") if i.args > 0: for link in i.args: if '.reddit.com/' in i.args[0].lower():", "if data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' % ( BOLD,", "| Score: %s | Comments: %s' \\ % (subreddit, score, comments), i )", "= ' [sticky]' if data['stickied'] else '' b.l_say( 'Reddit post: %s%s%s%s by %s%s%s'", "'Reddit post: %s%s%s%s by %s%s%s' % ( BOLD, title, sticky_status, RESET, BOLD, author,", "i ) b.l_say( 'Subreddit: %s | Score: %s | Comments: %s' \\ %", "score = data['score'] comments = data['num_comments'] mod_status = ' [M]' if data['distinguished'] ==", "b.l_say( 'Subreddit: %s | Score: %s | Comments: %s' \\ % (subreddit, score,", "parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>', i, 0) return True def reddit(l, b, i):", "'.reddit.com/' in ' '.join(m): input = bot.new_input(n, c, m) # Treat input as", "== 'moderator' else '' sticky_status = ' [sticky]' if data['stickied'] else '' b.l_say(", "= urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author'] subreddit =", "<link> !r user \"\"\" return parsereddit(l, b, i) def _chat(bot, args): n, c,", "c, m = args if '.reddit.com/' in ' '.join(m): input = bot.new_input(n, c,", "!a <link> !r user \"\"\" def parselink(link): meta_data_link = link + '.json' tables", "def reddit(l, b, i): \"\"\" !d Alias for .parsereddit !a <link> !r user", "return True def reddit(l, b, i): \"\"\" !d Alias for .parsereddit !a <link>", "!r user \"\"\" return parsereddit(l, b, i) def _chat(bot, args): n, c, m", "for link in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else: b.l_say('Usage: .parsereddit <link>',", "'.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author = data['author']", "title = data['title'] author = data['author'] subreddit = data['subreddit'] score = data['score'] comments", "m = args if '.reddit.com/' in ' '.join(m): input = bot.new_input(n, c, m)", "input as a command. input.set_command('parsereddit') input.set_level(1) input.set_user(bot.get_user(n)) input.args = [] # Handle multiple", "comments), i ) if i.args > 0: for link in i.args: if '.reddit.com/'", "_init(bot): print '\\t%s loaded' % __name__ def parsereddit(l, b, i): \"\"\" !d Parse", "a Reddit link into it's information !a <link> !r user \"\"\" def parselink(link):", "multiple links for word in m: if '.reddit.com/' in word: input.args.append(word) bot.plugins.process_command(bot, input)", "score, comments), i ) if i.args > 0: for link in i.args: if", "!a <link> !r user \"\"\" return parsereddit(l, b, i) def _chat(bot, args): n,", "i.args > 0: for link in i.args: if '.reddit.com/' in i.args[0].lower(): parselink(i.args[0].lower()) else:", "import BOLD, RESET def _init(bot): print '\\t%s loaded' % __name__ def parsereddit(l, b,", "i, 0) return True def reddit(l, b, i): \"\"\" !d Alias for .parsereddit", "[M]' if data['distinguished'] == 'moderator' else '' sticky_status = ' [sticky]' if data['stickied']", "data['score'] comments = data['num_comments'] mod_status = ' [M]' if data['distinguished'] == 'moderator' else", "= ' [M]' if data['distinguished'] == 'moderator' else '' sticky_status = ' [sticky]'", "link + '.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author", "'Subreddit: %s | Score: %s | Comments: %s' \\ % (subreddit, score, comments),", "Alias for .parsereddit !a <link> !r user \"\"\" return parsereddit(l, b, i) def", "mod_status = ' [M]' if data['distinguished'] == 'moderator' else '' sticky_status = '", "+ '.json' tables = urllib.urlopen(meta_data_link) data = json.loads(tables.read())[0]['data']['children'][0]['data'] title = data['title'] author =", "information !a <link> !r user \"\"\" def parselink(link): meta_data_link = link + '.json'", "IRC Bot reddit.py plugin module http://toofifty.me/oracle \"\"\" import urllib, json from format import", "plugin module http://toofifty.me/oracle \"\"\" import urllib, json from format import BOLD, RESET def", "!d Alias for .parsereddit !a <link> !r user \"\"\" return parsereddit(l, b, i)", "b.l_say( 'Reddit post: %s%s%s%s by %s%s%s' % ( BOLD, title, sticky_status, RESET, BOLD," ]
[ "(rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating", "+ str(total_reviews_received) + \",\" + str(address) + \",\" + str(lat) + \",\" +", "errors='ignore') + b\"\\n\") # Extract pagination url count = float(total_reviews_received)/10 if (count >", "\"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum taLnk \" })", "pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\")", "str(lat) + \",\" + str(lng) + \",\" + str(reviewer_nationality) + \",\" + str(rating)", "None): rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating =", "= 150 pagination_div = hotel_soup.find('div', { \"class\" : \"unified pagination north_star \"}) page_div", "TODO Add day_since_fetch column after finlaizing dataset # Extract review_title, review_title_div = review.find(\"div\",", "!= None): rating = 1 else: rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\":", "\"partial_entry\"}) if (partial_review == None): review = \"\" else: review = partial_review.text[:-6] review", "{\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"})", ": \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span',", "== None): total_reviews_received = \"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url", "city = \"\" postal_code = \"\" country = address_div.find('span', { \"class\" : \"country-name\"", "\"ui_bubble_rating bubble_30\"}) != None): rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) !=", "\"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all reviews aavailable on", "review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None): review_title = review_title_span.text else: review_title =", "review = partial_review.text[:-6] review = review.replace(\",\", \" \") review = review.replace(\"\\n\", \" \")", "= \"\" if ((page < count) & (len(pagination_spans) > 3)): page = page", "review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality = \"\" else: reviewer_nationality =", "taLnk \" }) next_url = \"\" if ((page < count) & (len(pagination_spans) >", "= street_address + \" \" + locality + \" \" + country address", "average_rating average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] #", "None): rating = 1 else: rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate", "hotel_soup.find('div', { \"class\" : \"unified pagination north_star \"}) page_div = hotel_soup.find('div', { \"class\"", "{\"class\": \"quote\"}) if (review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span", "# Extract average_rating average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating =", "{ \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum taLnk \"", "lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for script", "None): review = \"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review ==", "= 1 else: rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if", "review_title = review_title_span.text else: review_title = \"\" else: review_title = \"\" review_title =", "reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup =", "\"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date rating_div =", "urllib import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+", "{ \"class\" : \"locality\" }).text if (len(locality.split(' ')) > 2): city = locality.split('", "\"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', {", "reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"})", "{\"src\":False}) keys = ['lat', 'lng'] for script in all_script: all_value = script.string if", "a break for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\")", "(partial_review == None): review = \"\" else: review = partial_review.text[:-6] review = review.replace(\",\",", "if (review_div == None): review = \"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"})", "rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating = 3", "hotel_content in divs: # Extract name, url listing_title = hotel_content.find('div', { \"class\" :", "== None): rating = \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None):", "5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating = 4 elif (rating_div.find(\"span\",", "< count) & (len(pagination_spans) > 3)): page = page + 2 next_url =", "{ \"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span", "!= None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None): review_title =", "# Extract Address address_div = hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address", "\"review-container\"}) # Loop through all reviews aavailable on page for review in reviews:", "address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all", "= review_date_span[\"title\"] else: review_date = \"\" # TODO Add day_since_fetch column after finlaizing", "}).text locality = address_div.find('span', { \"class\" : \"locality\" }).text if (len(locality.split(' ')) >", "else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url +", "\"hotel_content easyClear sem\" }) for hotel_content in divs: # Extract name, url listing_title", "(reviewer_name_div == None): reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text", "{\"class\": \"partial_entry\"}) if (partial_review == None): review = \"\" else: review = partial_review.text[:-6]", "\"location\"}) if (reviewer_location_div == None): reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\":", "city = locality.split(' ')[0] postal_code = locality.split(' ')[1] else: city = \"\" postal_code", "str(average_rating) + \",\" + str(total_reviews_received) + \",\" + str(address) + \",\" + str(lat)", "street_address = address_div.find('span', { \"class\" : \"street-address\" }).text locality = address_div.find('span', { \"class\"", ": \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum taLnk \" }) next_url", "\"ui_bubble_rating bubble_10\"}) != None): rating = 1 else: rating = \"\" review_date_span =", "= \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until it", "sem\" }) for hotel_content in divs: # Extract name, url listing_title = hotel_content.find('div',", "{ \"class\" : \"street-address\" }).text locality = address_div.find('span', { \"class\" : \"locality\" }).text", "reviews_url reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\" }) if (reviews_span == None):", "+ str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination url count =", "reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract", "\",\" + str(rating) + \",\" +str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore')", "\") review = review.replace(\"\\n\", \" \") # Add Record record = str(name) +", "Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality =", "line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") # Extract Address address_div", "b\"\\n\") # Extract pagination url count = float(total_reviews_received)/10 if (count > 150): count", "4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating = 3 elif (rating_div.find(\"span\",", "\"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through", "3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating = 2 elif (rating_div.find(\"span\",", "page = 1 while True: # Extract Lat, Lng lat = lng =", "# Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None):", "+ \",\" + str(total_reviews_received) + \",\" + str(address) + \",\" + str(lat) +", "next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup =", "}) for hotel_content in divs: # Extract name, url listing_title = hotel_content.find('div', {", "address_div = hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', {", "locality + \" \" + country address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div',", "in keys: if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip()", "= review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div == None): reviewer_name = \"\" else:", "if (len(locality.split(' ')) > 2): city = locality.split(' ')[0] postal_code = locality.split(' ')[1]", "line in all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]): lat =", "urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\"", "\") # TODO Add review_words_count column after finlaizing dataset # Extract review review_div", "None): rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating =", "hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True: # Extract Lat, Lng", "importing libraries from bs4 import BeautifulSoup import urllib import os import urllib.request base_path", "elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating = 2 elif (rating_div.find(\"span\", {\"class\":", "b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site", "total_reviews_received = \"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href']", "= \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \"", "= \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None): review_date", "{\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None): review_date = review_date_span[\"title\"] else: review_date =", "(len(pagination_spans) > 3)): page = page + 2 next_url = pagination_spans[3]['data-href'] next_url =", "\"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \")", "Extract Lat, Lng lat = lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys", "+ country address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop", "= soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\" }) for hotel_content in divs:", "in WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', {", "\"class\" : \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating", "review = review.replace(\",\", \" \") review = review.replace(\"\\n\", \" \") # Add Record", "None): review = \"\" else: review = partial_review.text[:-6] review = review.replace(\",\", \" \")", "reviewItemInline\"}) if (rating_div == None): rating = \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating", "= urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\" : \"hotel_content", "review = \"\" else: review = partial_review.text[:-6] review = review.replace(\",\", \" \") review", "\"class\" : \"reviewCount\" }) if (reviews_span == None): total_reviews_received = \"0\" continue else:", "None): rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating =", "= locality.split(' ')[1] else: city = \"\" postal_code = \"\" country = address_div.find('span',", "= address_div.find('span', { \"class\" : \"locality\" }).text if (len(locality.split(' ')) > 2): city", "hotel_content.find('div', { \"class\" : \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text #", "= locality.split(' ')[0] postal_code = locality.split(' ')[1] else: city = \"\" postal_code =", "= line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng = lng.replace(\",\",", "pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum taLnk \" }) next_url = \"\"", "street_address + \" \" + locality + \" \" + country address =", "trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until it hits a break for page_url", "{\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"})", "Add day_since_fetch column after finlaizing dataset # Extract review_title, review_title_div = review.find(\"div\", {\"class\":", "url = listing_title.find('a')['href'] url = trip_advisor_url + url #Extract current_price_per_night price_div = hotel_content.find('div',", "\"\") # Extract Address address_div = hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"})", "+ \",\" + str(current_price_per_night) + \",\" + str(average_rating) + \",\" + str(total_reviews_received) +", "price_div = hotel_content.find('div', { \"class\" : \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night =", "keys: if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat", "bubble_40\"}) != None): rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None):", "= hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\"", "= \"\" else: review = partial_review.text[:-6] review = review.replace(\",\", \" \") review =", "= hotel_soup.find('div', { \"class\" : \"unified pagination north_star \"}) page_div = hotel_soup.find('div', {", "\"\" country = address_div.find('span', { \"class\" : \"country-name\" }).text address = street_address +", "+ \" \" + locality + \" \" + country address = address.replace(\",\",", "hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum taLnk", "Add review_words_count column after finlaizing dataset # Extract review review_div = review.find(\"div\", {\"class\":", "address_div.find('span', { \"class\" : \"street-address\" }).text locality = address_div.find('span', { \"class\" : \"locality\"", "2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating = 1 else: rating", "Extract pagination url count = float(total_reviews_received)/10 if (count > 150): count = 150", "libraries from bs4 import BeautifulSoup import urllib import os import urllib.request base_path =", "if (reviews_span == None): total_reviews_received = \"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\")", "\"\") lng = lng.replace(\",\", \"\") # Extract Address address_div = hotel_soup.find('div', { \"class\"", "\"street-address\" }).text locality = address_div.find('span', { \"class\" : \"locality\" }).text if (len(locality.split(' '))", "(all_value == None): continue for line in all_value.splitlines(): if line.split(':')[0].strip() in keys: if", "all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for script in all_script: all_value", "(review_div == None): review = \"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if", "= reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating", "rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating = 2", "reviews: # Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div ==", "relativeDate\"}) if (review_date_span != None): review_date = review_date_span[\"title\"] else: review_date = \"\" #", "if (all_value == None): continue for line in all_value.splitlines(): if line.split(':')[0].strip() in keys:", "else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") #", "\",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination url count", "address_div.find('span', { \"class\" : \"locality\" }).text if (len(locality.split(' ')) > 2): city =", "(review_title_span != None): review_title = review_title_span.text else: review_title = \"\" else: review_title =", "\"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until it hits", "= listing_title.find('a')['href'] url = trip_advisor_url + url #Extract current_price_per_night price_div = hotel_content.find('div', {", "2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup", "column after finlaizing dataset # Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if", "+ str(average_rating) + \",\" + str(total_reviews_received) + \",\" + str(address) + \",\" +", "for hotel_content in divs: # Extract name, url listing_title = hotel_content.find('div', { \"class\"", "partial_review.text[:-6] review = review.replace(\",\", \" \") review = review.replace(\"\\n\", \" \") # Add", "{\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"})", "= pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup = BeautifulSoup(hotel_page_source,", "all_value = script.string if (all_value == None): continue for line in all_value.splitlines(): if", "page = page + 2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url", "# importing libraries from bs4 import BeautifulSoup import urllib import os import urllib.request", "current_price_per_night = price_span.text # Extract average_rating average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\"", "{ \"class\" : \"pageNum taLnk \" }) next_url = \"\" if ((page <", "!= None): rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating", "# Loop through all reviews aavailable on page for review in reviews: #", "!= None): review_title = review_title_span.text else: review_title = \"\" else: review_title = \"\"", "{\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review = \"\" else: partial_review =", "#Extract current_price_per_night price_div = hotel_content.find('div', { \"class\" : \"price\" }) price_span = price_div.select_one(\"span\")", "= address_div.find('span', { \"class\" : \"country-name\" }).text address = street_address + \" \"", "trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until", "next_url = \"\" if ((page < count) & (len(pagination_spans) > 3)): page =", "\" \") # Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div ==", "\"rating reviewItemInline\"}) if (rating_div == None): rating = \"\" else: if (rating_div.find(\"span\", {\"class\":", "rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating = 1", "= hotel_content.find('span', { \"class\" : \"reviewCount\" }) if (reviews_span == None): total_reviews_received =", "& (len(pagination_spans) > 3)): page = page + 2 next_url = pagination_spans[3]['data-href'] next_url", "Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review", "if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else: lng", "}).text if (len(locality.split(' ')) > 2): city = locality.split(' ')[0] postal_code = locality.split('", "\"username mo\"}) if (reviewer_name_div == None): reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\",", "name, url listing_title = hotel_content.find('div', { \"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0]", "= hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all reviews aavailable on page for", "= reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if", "\",\" + str(lng) + \",\" + str(reviewer_nationality) + \",\" + str(rating) + \",\"", "listing_title.find('a')['href'] url = trip_advisor_url + url #Extract current_price_per_night price_div = hotel_content.find('div', { \"class\"", "}).text address = street_address + \" \" + locality + \" \" +", "partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None): review = \"\" else:", "150): count = 150 pagination_div = hotel_soup.find('div', { \"class\" : \"unified pagination north_star", "= reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality", "keys[0]): lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng", "{\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date rating_div", "lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") # Extract", "review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None): review_title_span = review_title_div.find(\"span\",", "= average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\"", "review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if", "= hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for script in all_script: all_value =", "')[0] postal_code = locality.split(' ')[1] else: city = \"\" postal_code = \"\" country", "column after finlaizing dataset # Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"})", "if (count > 150): count = 150 pagination_div = hotel_soup.find('div', { \"class\" :", "reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\",", "\" \") review = review.replace(\"\\n\", \" \") # Add Record record = str(name)", "None): rating = \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating", "= lng.replace(\",\", \"\") # Extract Address address_div = hotel_soup.find('div', { \"class\" : \"prw_rup", "\",\" +str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract", "hits a break for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source,", "}) if (reviews_span == None): total_reviews_received = \"0\" continue else: total_reviews_received = reviews_span.text.split('", "bs4 import BeautifulSoup import urllib import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file", "== keys[0]): lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\")", "None): review_title = review_title_span.text else: review_title = \"\" else: review_title = \"\" review_title", "{\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div =", "\"class\" : \"country-name\" }).text address = street_address + \" \" + locality +", "= BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\" })", "for script in all_script: all_value = script.string if (all_value == None): continue for", "!= None): rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating", "reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div", "\" + country address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) #", "os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [", "+ reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while", "(rating_div == None): rating = \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) !=", "review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None): review_title = review_title_span.text else:", "\"\" if ((page < count) & (len(pagination_spans) > 3)): page = page +", "print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup", "= review_title.replace(\",\", \" \") # TODO Add review_words_count column after finlaizing dataset #", "}) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating average_rating_div = hotel_content.find('div',", "else: review = partial_review.text[:-6] review = review.replace(\",\", \" \") review = review.replace(\"\\n\", \"", "print(name) url = listing_title.find('a')['href'] url = trip_advisor_url + url #Extract current_price_per_night price_div =", "hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for script in all_script: all_value = script.string", "= float(total_reviews_received)/10 if (count > 150): count = 150 pagination_div = hotel_soup.find('div', {", "url listing_title = hotel_content.find('div', { \"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0] name", "review = \"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None):", "site until it hits a break for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read()", "\") # Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None):", "= review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div == None): rating = \"\" else:", "> 150): count = 150 pagination_div = hotel_soup.find('div', { \"class\" : \"unified pagination", "(review_date_span != None): review_date = review_date_span[\"title\"] else: review_date = \"\" # TODO Add", "= review.replace(\",\", \" \") review = review.replace(\"\\n\", \" \") # Add Record record", "review.replace(\",\", \" \") review = review.replace(\"\\n\", \" \") # Add Record record =", "+ str(reviewer_nationality) + \",\" + str(rating) + \",\" +str(review_title) + \",\" + str(review)", "3)): page = page + 2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url +", "= review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None): review_title = review_title_span.text else: review_title", "hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url", "2): city = locality.split(' ')[0] postal_code = locality.split(' ')[1] else: city = \"\"", "{\"class\": \"rating reviewItemInline\"}) if (rating_div == None): rating = \"\" else: if (rating_div.find(\"span\",", "BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True: # Extract Lat, Lng lat =", "review_date_span[\"title\"] else: review_date = \"\" # TODO Add day_since_fetch column after finlaizing dataset", "if (partial_review == None): review = \"\" else: review = partial_review.text[:-6] review =", "+ \",\" +str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") #", "reviews aavailable on page for review in reviews: # Extract reviewer_name reviewer_name_div =", "# looping through each site until it hits a break for page_url in", "= lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for", "each site until it hits a break for page_url in WebSites: page_source =", "{ \"class\" : \"hotel_content easyClear sem\" }) for hotel_content in divs: # Extract", "continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url", "name = name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url = trip_advisor_url + url", ": \"listing_title\" }) name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url =", "= 1 while True: # Extract Lat, Lng lat = lng = \"\"", "base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites", "line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\")", "count) & (len(pagination_spans) > 3)): page = page + 2 next_url = pagination_spans[3]['data-href']", "postal_code = \"\" country = address_div.find('span', { \"class\" : \"country-name\" }).text address =", "if (review_date_span != None): review_date = review_date_span[\"title\"] else: review_date = \"\" # TODO", "\"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div = review.find('div',", "page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\" :", "\"class\" : \"locality\" }).text if (len(locality.split(' ')) > 2): city = locality.split(' ')[0]", "current_price_per_night price_div = hotel_content.find('div', { \"class\" : \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night", "\"\" # TODO Add day_since_fetch column after finlaizing dataset # Extract review_title, review_title_div", "price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating average_rating_div = hotel_content.find('div', {", "}) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\"", "lng.replace(\",\", \"\") # Extract Address address_div = hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl", "lat = lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng']", "'lng'] for script in all_script: all_value = script.string if (all_value == None): continue", "= address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all reviews", "# Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div == None):", "None): reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality =", "str(current_price_per_night) + \",\" + str(average_rating) + \",\" + str(total_reviews_received) + \",\" + str(address)", "for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs =", "')) > 2): city = locality.split(' ')[0] postal_code = locality.split(' ')[1] else: city", "in all_script: all_value = script.string if (all_value == None): continue for line in", "review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review = \"\" else: partial_review", "= 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating = 4 elif", "in all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip()", "review = review.replace(\"\\n\", \" \") # Add Record record = str(name) + \",\"", "')[1] else: city = \"\" postal_code = \"\" country = address_div.find('span', { \"class\"", "\"ui_bubble_rating bubble_40\"}) != None): rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) !=", "= partial_review.text[:-6] review = review.replace(\",\", \" \") review = review.replace(\"\\n\", \" \") #", "reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True:", "= trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page =", "\",\" + str(average_rating) + \",\" + str(total_reviews_received) + \",\" + str(address) + \",\"", "prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\" : \"street-address\" }).text locality = address_div.find('span',", "{\"class\": \"username mo\"}) if (reviewer_name_div == None): reviewer_name = \"\" else: reviewer_name =", "> 3)): page = page + 2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url", "\"ui_bubble_rating bubble_50\"}) != None): rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) !=", "else: review_date = \"\" # TODO Add day_since_fetch column after finlaizing dataset #", ": \"locality\" }).text if (len(locality.split(' ')) > 2): city = locality.split(' ')[0] postal_code", "= [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until it hits a break", "else: city = \"\" postal_code = \"\" country = address_div.find('span', { \"class\" :", "= \"\" # TODO Add day_since_fetch column after finlaizing dataset # Extract review_title,", "\"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review = \"\" else: partial_review = review_div.find(\"p\",", ": \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating average_rating_div", "price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating average_rating_div = hotel_content.find('div', { \"class\" :", "# Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\" }) if", "{\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"})", "{\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\",", "rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating = 4", "> 2): city = locality.split(' ')[0] postal_code = locality.split(' ')[1] else: city =", "review_title = \"\" else: review_title = \"\" review_title = review_title.replace(\",\", \" \") #", "review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review =", "all reviews aavailable on page for review in reviews: # Extract reviewer_name reviewer_name_div", "= str(name) + \",\" + str(current_price_per_night) + \",\" + str(average_rating) + \",\" +", "(rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating", "\"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None): review_date =", "os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url", "reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div", "= \"\" postal_code = \"\" country = address_div.find('span', { \"class\" : \"country-name\" }).text", "+ str(lat) + \",\" + str(lng) + \",\" + str(reviewer_nationality) + \",\" +", "Lat, Lng lat = lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys =", "finlaizing dataset # Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div !=", "prw_reviews_text_summary_hsx\"}) if (review_div == None): review = \"\" else: partial_review = review_div.find(\"p\", {\"class\":", "== None): reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name", "pagination url count = float(total_reviews_received)/10 if (count > 150): count = 150 pagination_div", "while True: # Extract Lat, Lng lat = lng = \"\" all_script =", "\" \") # Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if", "listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url = trip_advisor_url +", "= BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True: # Extract Lat, Lng lat", "after finlaizing dataset # Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if", "divs: # Extract name, url listing_title = hotel_content.find('div', { \"class\" : \"listing_title\" })", "divs = soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\" }) for hotel_content in", "if (rating_div == None): rating = \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"})", "average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\" })", "+ str(rating) + \",\" +str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') +", "Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\" }) if (reviews_span", "+ \",\" + str(address) + \",\" + str(lat) + \",\" + str(lng) +", "encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination url count = float(total_reviews_received)/10 if (count", "{ \"class\" : \"unified pagination north_star \"}) page_div = hotel_soup.find('div', { \"class\" :", "review_title = \"\" review_title = review_title.replace(\",\", \" \") # TODO Add review_words_count column", "\"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating = 5 elif", "= trip_advisor_url + url #Extract current_price_per_night price_div = hotel_content.find('div', { \"class\" : \"price\"", "\" \") # Add Record record = str(name) + \",\" + str(current_price_per_night) +", "# Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality", "+ \",\" + str(rating) + \",\" +str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\",", "\"}) page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\"", "country = address_div.find('span', { \"class\" : \"country-name\" }).text address = street_address + \"", "WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\"", "= review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review = \"\" else:", "{\"class\": \"review-container\"}) # Loop through all reviews aavailable on page for review in", "= \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \"", "reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality = \"\"", "dataset # Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div ==", "= open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] #", "\"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\" : \"street-address\" }).text locality =", "<reponame>adnanalimurtaza/tripadvisor_data_scraper<filename>scraper.py<gh_stars>1-10 # importing libraries from bs4 import BeautifulSoup import urllib import os import", "\"class\" : \"unified pagination north_star \"}) page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"})", "{\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating = 1 else: rating = \"\" review_date_span", "{ \"class\" : \"country-name\" }).text address = street_address + \" \" + locality", "line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else: lng =", "else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None): review = \"\"", "\"quote\"}) if (review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span !=", "hotel_content.find('div', { \"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\")", "average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\" :", "through each site until it hits a break for page_url in WebSites: page_source", "headerBL\"}) street_address = address_div.find('span', { \"class\" : \"street-address\" }).text locality = address_div.find('span', {", "= hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received,", "# Extract pagination url count = float(total_reviews_received)/10 if (count > 150): count =", "lat = lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") # Extract Address address_div =", "rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None):", "= \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for script in", "(reviews_span == None): total_reviews_received = \"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received)", "for review in reviews: # Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"})", "+ 2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read()", "\"locality\" }).text if (len(locality.split(' ')) > 2): city = locality.split(' ')[0] postal_code =", "reviewer_name = reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\": \"location\"})", "open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping", "\"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat', 'lng'] for script in all_script:", "\",\" + str(current_price_per_night) + \",\" + str(average_rating) + \",\" + str(total_reviews_received) + \",\"", "+ \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination url", "through all reviews aavailable on page for review in reviews: # Extract reviewer_name", "else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") #", "for line in all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]): lat", "= script.string if (all_value == None): continue for line in all_value.splitlines(): if line.split(':')[0].strip()", "trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") else: break file.close()", "total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url", "= listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url = trip_advisor_url", "rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None): review_date = review_date_span[\"title\"] else: review_date", "else: lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") #", "(count > 150): count = 150 pagination_div = hotel_soup.find('div', { \"class\" : \"unified", "reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div == None): reviewer_name = \"\"", "(rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating", "looping through each site until it hits a break for page_url in WebSites:", "1 else: rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span", ": \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\" : \"street-address\" }).text locality", "((page < count) & (len(pagination_spans) > 3)): page = page + 2 next_url", "bubble_10\"}) != None): rating = 1 else: rating = \"\" review_date_span = rating_div.find(\"span\",", "if (review_title_span != None): review_title = review_title_span.text else: review_title = \"\" else: review_title", "+ \",\" + str(average_rating) + \",\" + str(total_reviews_received) + \",\" + str(address) +", "review_title.replace(\",\", \" \") # TODO Add review_words_count column after finlaizing dataset # Extract", "urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True: # Extract Lat,", "easyClear sem\" }) for hotel_content in divs: # Extract name, url listing_title =", "== None): reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality", "Extract name, url listing_title = hotel_content.find('div', { \"class\" : \"listing_title\" }) name =", "reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\":", "reviews_url = trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page", "[ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until it hits a break for", "None): reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name =", "= \"\" review_title = review_title.replace(\",\", \" \") # TODO Add review_words_count column after", "bubble_50\"}) != None): rating = 5 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None):", "\"reviewCount\" }) if (reviews_span == None): total_reviews_received = \"0\" continue else: total_reviews_received =", "\"lxml\") divs = soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\" }) for hotel_content", "(rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating = 1 else: rating = \"\"", "review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div == None): review = \"\"", "\"class\" : \"hotel_content easyClear sem\" }) for hotel_content in divs: # Extract name,", "= price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating average_rating_div = hotel_content.find('div', { \"class\"", "reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all reviews aavailable on page", "= 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None): rating = 2 elif", "# Extract Lat, Lng lat = lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False})", "until it hits a break for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup", "\",\" + str(address) + \",\" + str(lat) + \",\" + str(lng) + \",\"", "import BeautifulSoup import urllib import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file =", "150 pagination_div = hotel_soup.find('div', { \"class\" : \"unified pagination north_star \"}) page_div =", "\"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\" : \"street-address\" }).text", "urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\" : \"hotel_content easyClear", "WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each site until it hits a", "\" }) next_url = \"\" if ((page < count) & (len(pagination_spans) > 3)):", "after finlaizing dataset # Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div", ": \"country-name\" }).text address = street_address + \" \" + locality + \"", "\"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract average_rating average_rating_div =", "all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else:", "break for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs", "\"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None): review =", "record = str(name) + \",\" + str(current_price_per_night) + \",\" + str(average_rating) + \",\"", "it hits a break for page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup =", "= reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source,", "else: review_title = \"\" review_title = review_title.replace(\",\", \" \") # TODO Add review_words_count", "str(total_reviews_received) + \",\" + str(address) + \",\" + str(lat) + \",\" + str(lng)", "= review_title_span.text else: review_title = \"\" else: review_title = \"\" review_title = review_title.replace(\",\",", "review_title_span.text else: review_title = \"\" else: review_title = \"\" review_title = review_title.replace(\",\", \"", "\" + locality + \" \" + country address = address.replace(\",\", \"\") reviews", "(rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating", "locality.split(' ')[0] postal_code = locality.split(' ')[1] else: city = \"\" postal_code = \"\"", "review_date = \"\" # TODO Add day_since_fetch column after finlaizing dataset # Extract", "str(lng) + \",\" + str(reviewer_nationality) + \",\" + str(rating) + \",\" +str(review_title) +", "country address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through", "rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div == None): rating", "+ str(lng) + \",\" + str(reviewer_nationality) + \",\" + str(rating) + \",\" +str(review_title)", "+str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination", "rating = 1 else: rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"})", "= hotel_content.find('div', { \"class\" : \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text", "(reviewer_location_div == None): reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text", "bubble_20\"}) != None): rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None):", "import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\")", "\",\" + str(reviewer_nationality) + \",\" + str(rating) + \",\" +str(review_title) + \",\" +", "str(name) + \",\" + str(current_price_per_night) + \",\" + str(average_rating) + \",\" + str(total_reviews_received)", "TODO Add review_words_count column after finlaizing dataset # Extract review review_div = review.find(\"div\",", "name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url =", "= \"\" country = address_div.find('span', { \"class\" : \"country-name\" }).text address = street_address", "= review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"})", "\"class\" : \"pageNum taLnk \" }) next_url = \"\" if ((page < count)", "file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination url count = float(total_reviews_received)/10 if", "!= None): rating = 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating", "soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\" }) for hotel_content in divs: #", "script.string if (all_value == None): continue for line in all_value.splitlines(): if line.split(':')[0].strip() in", "url count = float(total_reviews_received)/10 if (count > 150): count = 150 pagination_div =", "\"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum taLnk \" }) next_url =", "== None): review = \"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review", "\"unified pagination north_star \"}) page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans =", "aavailable on page for review in reviews: # Extract reviewer_name reviewer_name_div = review.find('div',", "{ \"class\" : \"reviewCount\" }) if (reviews_span == None): total_reviews_received = \"0\" continue", "reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div == None): reviewer_name =", "if (reviewer_name_div == None): reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline", "= os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites =", "= review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality = \"\" else: reviewer_nationality", "!= None): review_date = review_date_span[\"title\"] else: review_date = \"\" # TODO Add day_since_fetch", "mo\"}) if (reviewer_name_div == None): reviewer_name = \"\" else: reviewer_name = reviewer_name_div.find(\"span\", {\"class\":", "\" \") # TODO Add review_words_count column after finlaizing dataset # Extract review", "pagination north_star \"}) page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span',", "day_since_fetch column after finlaizing dataset # Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"})", "Lng lat = lng = \"\" all_script = hotel_soup.find_all(\"script\", {\"src\":False}) keys = ['lat',", "Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div == None):", "if ((page < count) & (len(pagination_spans) > 3)): page = page + 2", "in divs: # Extract name, url listing_title = hotel_content.find('div', { \"class\" : \"listing_title\"", "\"listing_title\" }) name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href']", "== None): review = \"\" else: review = partial_review.text[:-6] review = review.replace(\",\", \"", "}) next_url = \"\" if ((page < count) & (len(pagination_spans) > 3)): page", "\"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url =", "\"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url", "= ['lat', 'lng'] for script in all_script: all_value = script.string if (all_value ==", "lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng =", "\"\" review_title = review_title.replace(\",\", \" \") # TODO Add review_words_count column after finlaizing", "north_star \"}) page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', {", "= review.replace(\"\\n\", \" \") # Add Record record = str(name) + \",\" +", "listing_title = hotel_content.find('div', { \"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0] name =", "\") # Add Record record = str(name) + \",\" + str(current_price_per_night) + \",\"", "\"pageNum taLnk \" }) next_url = \"\" if ((page < count) & (len(pagination_spans)", "name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url = trip_advisor_url + url #Extract current_price_per_night", "\"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \")", "all_script: all_value = script.string if (all_value == None): continue for line in all_value.splitlines():", "(review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None): review_title", "import urllib import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\")", "file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"]", "address_div.find('span', { \"class\" : \"country-name\" }).text address = street_address + \" \" +", "= \"\" else: review_title = \"\" review_title = review_title.replace(\",\", \" \") # TODO", "from bs4 import BeautifulSoup import urllib import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__'))", "{ \"class\" : \"price\" }) price_span = price_div.select_one(\"span\") current_price_per_night = price_span.text # Extract", "else: review_title = \"\" else: review_title = \"\" review_title = review_title.replace(\",\", \" \")", "Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None): review_title_span =", "{\"class\": \"noQuotes\"}) if (review_title_span != None): review_title = review_title_span.text else: review_title = \"\"", "= urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True: # Extract", "Extract average_rating average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"]", "rating = \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating =", "= rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None): review_date = review_date_span[\"title\"] else:", "str(address) + \",\" + str(lat) + \",\" + str(lng) + \",\" + str(reviewer_nationality)", "review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div == None): reviewer_name = \"\" else: reviewer_name", "continue for line in all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() == keys[0]):", "review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\":", "address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all reviews aavailable", "\"class\" : \"street-address\" }).text locality = address_div.find('span', { \"class\" : \"locality\" }).text if", "review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None): review = \"\" else: review =", "pagination_div = hotel_soup.find('div', { \"class\" : \"unified pagination north_star \"}) page_div = hotel_soup.find('div',", "page + 2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source =", "dataset # Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None):", "hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\" :", "\"lxml\") page = 1 while True: # Extract Lat, Lng lat = lng", "\"noQuotes\"}) if (review_title_span != None): review_title = review_title_span.text else: review_title = \"\" else:", "Address address_div = hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span',", "}) name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url", "Extract Address address_div = hotel_soup.find('div', { \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address =", "rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div == None): rating = \"\"", "(line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat = lat.replace(\",\",", "= reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer,", "hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1 while True: #", "# Extract review_title, review_title_div = review.find(\"div\", {\"class\": \"quote\"}) if (review_title_div != None): review_title_span", "None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None): review_title = review_title_span.text", "str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\") # Extract pagination url count = float(total_reviews_received)/10", "hotel_soup.find_all('div', {\"class\": \"review-container\"}) # Loop through all reviews aavailable on page for review", "hotel_content.find('span', { \"class\" : \"reviewCount\" }) if (reviews_span == None): total_reviews_received = \"0\"", "+ url #Extract current_price_per_night price_div = hotel_content.find('div', { \"class\" : \"price\" }) price_span", "reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\")", "import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"), \"wb\") file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url =", "Record record = str(name) + \",\" + str(current_price_per_night) + \",\" + str(average_rating) +", "Add Record record = str(name) + \",\" + str(current_price_per_night) + \",\" + str(average_rating)", "price_span.text # Extract average_rating average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating", "\"\" postal_code = \"\" country = address_div.find('span', { \"class\" : \"country-name\" }).text address", "None): review_date = review_date_span[\"title\"] else: review_date = \"\" # TODO Add day_since_fetch column", "elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating = 3 elif (rating_div.find(\"span\", {\"class\":", "Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div == None): reviewer_name", "{ \"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0] name = name.replace(\",\", \"\") print(name)", "\"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract total_reviews_received, reviews_url reviews_span =", "BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\" }) for", "None): rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating =", "['lat', 'lng'] for script in all_script: all_value = script.string if (all_value == None):", "next_url = trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") else:", "None): continue for line in all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip() ==", "address = street_address + \" \" + locality + \" \" + country", "elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_40\"}) != None): rating = 4 elif (rating_div.find(\"span\", {\"class\":", "+ b\"\\n\") # Extract pagination url count = float(total_reviews_received)/10 if (count > 150):", "# TODO Add day_since_fetch column after finlaizing dataset # Extract review_title, review_title_div =", "review.replace(\"\\n\", \" \") # Add Record record = str(name) + \",\" + str(current_price_per_night)", "True: # Extract Lat, Lng lat = lng = \"\" all_script = hotel_soup.find_all(\"script\",", "= lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") # Extract Address address_div = hotel_soup.find('div',", "BeautifulSoup import urllib import os import urllib.request base_path = os.path.dirname(os.path.abspath('__file__')) file = open(os.path.expanduser(r\"\"+base_path+\"/datasets/Hotels_Reviews.csv\"),", "\") # Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div", "str(rating) + \",\" +str(review_title) + \",\" + str(review) file.write(bytes(record, encoding=\"ascii\", errors='ignore') + b\"\\n\")", "finlaizing dataset # Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup prw_reviews_text_summary_hsx\"}) if (review_div", "= line.split(':')[1].strip() lat = lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") # Extract Address", "= reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source", "# Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div ==", "# Extract name, url listing_title = hotel_content.find('div', { \"class\" : \"listing_title\" }) name", "!= None): rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating", "\",\" + str(total_reviews_received) + \",\" + str(address) + \",\" + str(lat) + \",\"", "+ str(address) + \",\" + str(lat) + \",\" + str(lng) + \",\" +", ": \"street-address\" }).text locality = address_div.find('span', { \"class\" : \"locality\" }).text if (len(locality.split('", "review_date = review_date_span[\"title\"] else: review_date = \"\" # TODO Add day_since_fetch column after", "trip_advisor_url + url #Extract current_price_per_night price_div = hotel_content.find('div', { \"class\" : \"price\" })", "page_div.find_all('span', { \"class\" : \"pageNum taLnk \" }) next_url = \"\" if ((page", "file.write(b\"name,current_price_per_night,average_rating,total_reviews_received,address,lat,lng,reviewer_nationality,rating,review_title,review\"+ b\"\\n\") trip_advisor_url = \"https://www.tripadvisor.com\" WebSites = [ trip_advisor_url+\"/Hotels-g189896-Finland-Hotels.html\"] # looping through each", "postal_code = locality.split(' ')[1] else: city = \"\" postal_code = \"\" country =", "+ locality + \" \" + country address = address.replace(\",\", \"\") reviews =", "\"ui_bubble_rating bubble_20\"}) != None): rating = 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) !=", "count = 150 pagination_div = hotel_soup.find('div', { \"class\" : \"unified pagination north_star \"})", "soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div', { \"class\" : \"hotel_content easyClear sem\"", "url = trip_advisor_url + url #Extract current_price_per_night price_div = hotel_content.find('div', { \"class\" :", "\"\" else: review = partial_review.text[:-6] review = review.replace(\",\", \" \") review = review.replace(\"\\n\",", "str(reviewer_nationality) + \",\" + str(rating) + \",\" +str(review_title) + \",\" + str(review) file.write(bytes(record,", "elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating = 1 else: rating =", "reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\" }) if (reviews_span == None): total_reviews_received", "average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\" }) average_rating = average_rating_div.select_one(\"span\")[\"content\"] # Extract", "on page for review in reviews: # Extract reviewer_name reviewer_name_div = review.find('div', {\"class\":", "review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div == None): rating = \"\" else: if", "locality = address_div.find('span', { \"class\" : \"locality\" }).text if (len(locality.split(' ')) > 2):", "= page_div.find_all('span', { \"class\" : \"pageNum taLnk \" }) next_url = \"\" if", "reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date", "review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span != None): review_date = review_date_span[\"title\"]", "float(total_reviews_received)/10 if (count > 150): count = 150 pagination_div = hotel_soup.find('div', { \"class\"", "+ \",\" + str(lng) + \",\" + str(reviewer_nationality) + \",\" + str(rating) +", "if (review_title_div != None): review_title_span = review_title_div.find(\"span\", {\"class\": \"noQuotes\"}) if (review_title_span != None):", "reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source =", "script in all_script: all_value = script.string if (all_value == None): continue for line", "= page + 2 next_url = pagination_spans[3]['data-href'] next_url = trip_advisor_url + next_url hotel_page_source", "\"ratingDate relativeDate\"}) if (review_date_span != None): review_date = review_date_span[\"title\"] else: review_date = \"\"", "= name.replace(\",\", \"\") print(name) url = listing_title.find('a')['href'] url = trip_advisor_url + url #Extract", ": \"reviewCount\" }) if (reviews_span == None): total_reviews_received = \"0\" continue else: total_reviews_received", "= hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" : \"pageNum", "= hotel_content.find('div', { \"class\" : \"listing_title\" }) name = listing_title.find('a').contents[0] name = name.replace(\",\",", ": \"unified pagination north_star \"}) page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans", "(len(locality.split(' ')) > 2): city = locality.split(' ')[0] postal_code = locality.split(' ')[1] else:", "if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating = 5 elif (rating_div.find(\"span\", {\"class\":", "in reviews: # Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if (reviewer_name_div", "\" \" + locality + \" \" + country address = address.replace(\",\", \"\")", "userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\", \" \") # Extract rating_given_by_reviewer, review_date rating_div = review.find(\"div\",", "= trip_advisor_url + next_url hotel_page_source = urllib.request.urlopen(next_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") else: break", "else: rating = \"\" review_date_span = rating_div.find(\"span\", {\"class\": \"ratingDate relativeDate\"}) if (review_date_span !=", "= review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None): review = \"\" else: review", "review in reviews: # Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username mo\"}) if", "= \"\" else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating = 5", "= \"\" else: partial_review = review_div.find(\"p\", {\"class\": \"partial_entry\"}) if (partial_review == None): review", "= address_div.find('span', { \"class\" : \"street-address\" }).text locality = address_div.find('span', { \"class\" :", "count = float(total_reviews_received)/10 if (count > 150): count = 150 pagination_div = hotel_soup.find('div',", "{ \"class\" : \"prw_rup prw_common_atf_header_bl headerBL\"}) street_address = address_div.find('span', { \"class\" : \"street-address\"", "lng = lng.replace(\",\", \"\") # Extract Address address_div = hotel_soup.find('div', { \"class\" :", "\"\") print(name) url = listing_title.find('a')['href'] url = trip_advisor_url + url #Extract current_price_per_night price_div", "+ str(current_price_per_night) + \",\" + str(average_rating) + \",\" + str(total_reviews_received) + \",\" +", "None): total_reviews_received = \"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url =", ": \"hotel_content easyClear sem\" }) for hotel_content in divs: # Extract name, url", "= \"0\" continue else: total_reviews_received = reviews_span.text.split(' ')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url", "bubble_30\"}) != None): rating = 3 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_20\"}) != None):", "page for review in reviews: # Extract reviewer_name reviewer_name_div = review.find('div', {\"class\": \"username", "lat.replace(\",\", \"\") lng = lng.replace(\",\", \"\") # Extract Address address_div = hotel_soup.find('div', {", "== None): continue for line in all_value.splitlines(): if line.split(':')[0].strip() in keys: if (line.split(':')[0].strip()", "page_div = hotel_soup.find('div', { \"class\" : \"pageNumbers\"}) pagination_spans = page_div.find_all('span', { \"class\" :", "total_reviews_received, reviews_url reviews_span = hotel_content.find('span', { \"class\" : \"reviewCount\" }) if (reviews_span ==", "else: if (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_50\"}) != None): rating = 5 elif (rating_div.find(\"span\",", "if (reviewer_location_div == None): reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline", "# TODO Add review_words_count column after finlaizing dataset # Extract review review_div =", "= 4 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_30\"}) != None): rating = 3 elif", ": \"pageNum taLnk \" }) next_url = \"\" if ((page < count) &", "\"\" else: review_title = \"\" review_title = review_title.replace(\",\", \" \") # TODO Add", "\",\" + str(lat) + \",\" + str(lng) + \",\" + str(reviewer_nationality) + \",\"", "review_date rating_div = review.find(\"div\", {\"class\": \"rating reviewItemInline\"}) if (rating_div == None): rating =", "page_url in WebSites: page_source = urllib.request.urlopen(page_url).read() soup = BeautifulSoup(page_source, \"lxml\") divs = soup.find_all('div',", "\" \" + country address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\": \"review-container\"})", "reviewer_name = reviewer_name_div.find(\"span\", {\"class\": \"expand_inline scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") # Extract", "if (line.split(':')[0].strip() == keys[0]): lat = line.split(':')[1].strip() else: lng = line.split(':')[1].strip() lat =", "# Add Record record = str(name) + \",\" + str(current_price_per_night) + \",\" +", "url #Extract current_price_per_night price_div = hotel_content.find('div', { \"class\" : \"price\" }) price_span =", "= 2 elif (rating_div.find(\"span\", {\"class\": \"ui_bubble_rating bubble_10\"}) != None): rating = 1 else:", "reviewer_location_div = review.find('div', {\"class\": \"location\"}) if (reviewer_location_div == None): reviewer_nationality = \"\" else:", "review_title = review_title.replace(\",\", \" \") # TODO Add review_words_count column after finlaizing dataset", "1 while True: # Extract Lat, Lng lat = lng = \"\" all_script", "Loop through all reviews aavailable on page for review in reviews: # Extract", "+ \",\" + str(lat) + \",\" + str(lng) + \",\" + str(reviewer_nationality) +", "scrname\"}).text reviewer_name = reviewer_name.replace(\",\", \" \") # Extract reviewer_nationality reviewer_location_div = review.find('div', {\"class\":", "reviewer_nationality = \"\" else: reviewer_nationality = reviewer_location_div.find(\"span\", {\"class\": \"expand_inline userLocation\"}).text reviewer_nationality = reviewer_nationality.replace(\",\",", "keys = ['lat', 'lng'] for script in all_script: all_value = script.string if (all_value", "locality.split(' ')[1] else: city = \"\" postal_code = \"\" country = address_div.find('span', {", "+ \" \" + country address = address.replace(\",\", \"\") reviews = hotel_soup.find_all('div', {\"class\":", "\"country-name\" }).text address = street_address + \" \" + locality + \" \"", "+ \",\" + str(reviewer_nationality) + \",\" + str(rating) + \",\" +str(review_title) + \",\"", "review_words_count column after finlaizing dataset # Extract review review_div = review.find(\"div\", {\"class\": \"prw_rup", "= price_span.text # Extract average_rating average_rating_div = hotel_content.find('div', { \"class\" : \"bubbleRating\" })", "trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read() hotel_soup = BeautifulSoup(hotel_page_source, \"lxml\") page = 1", "')[0].replace(\",\",\"\") print(total_reviews_received) reviews_url = reviews_span.find('a')['href'] reviews_url = trip_advisor_url + reviews_url hotel_page_source = urllib.request.urlopen(reviews_url).read()" ]
[ "for Golden Gate \"\"\" # First check that we are running in a", "ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are set up, set the config. ns.configure(config)", "is within and assume that's the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\")", "config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon)", "the 'gg' conda environment, please check the 'Getting Started' guide for more details", "that we are running in a Python >= 3.5 environment from __future__ import", "ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\")", "Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean)", "not sys.version_info.major == 3 and sys.version_info.minor >= 5: print( \"\"\"You are using 'invoke'", "3.5 is required. You have probably not activated the 'gg' conda environment, please", "Gate \"\"\" # First check that we are running in a Python >=", "to setup your environment\"\"\") sys.exit(1) # Imports import os import subprocess from invoke", "# Copyright 2017-2020 Fitbit, Inc # SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden", ">= 3.5 is required. You have probably not activated the 'gg' conda environment,", ". import native from . import clean from . import wasm from .", "be at the root of the repo. Thus, find the folder .git/ is", "and assume that's the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR =", "submodules) # will be at the root of the repo. Thus, find the", "ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are set up, set the", "are running in a Python >= 3.5 environment from __future__ import print_function import", "of '.git', the .git/ folder (even for submodules) # will be at the", "android from . import apple from . import pylon from . import native", "print( \"\"\"You are using 'invoke' in a Python 2.x environment, but Python >=", "from . import docker # Assuming you haven't moved the default location of", "will be at the root of the repo. Thus, find the folder .git/", "using 'invoke' in a Python 2.x environment, but Python >= 3.5 is required.", "dot notation, since there is a paths() function # on a Config object.", "os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE,", "= os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR =", "paths variable by using dot notation, since there is a paths() function #", "environment\"\"\") sys.exit(1) # Imports import os import subprocess from invoke import Collection, Config,", "# After collections are set up, set the config. ns.configure(config) ns.configure(android.config) ns.configure(apple.config) ns.configure(pylon.config)", "http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR", "native from . import clean from . import wasm from . import doc", "import clean from . import wasm from . import doc from . import", "your environment\"\"\") sys.exit(1) # Imports import os import subprocess from invoke import Collection,", "guide for more details on how to setup your environment\"\"\") sys.exit(1) # Imports", "Config object. We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR", "cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR", "cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR", "access the paths variable by using dot notation, since there is a paths()", "from . import native from . import clean from . import wasm from", "Config, task from . import android from . import apple from . import", "--show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants that are common among all", "if not sys.version_info.major == 3 and sys.version_info.minor >= 5: print( \"\"\"You are using", "is required. You have probably not activated the 'gg' conda environment, please check", "= {} # We can't access the paths variable by using dot notation,", "# Imports import os import subprocess from invoke import Collection, Config, task from", "from . import pylon from . import native from . import clean from", "We can't access the paths variable by using dot notation, since there is", "ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are set", "5: print( \"\"\"You are using 'invoke' in a Python 2.x environment, but Python", "is a paths() function # on a Config object. We much use Dictionary", "os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR,", "\"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns", "configuration for Golden Gate \"\"\" # First check that we are running in", "\"\"\"You are using 'invoke' in a Python 2.x environment, but Python >= 3.5", "moved the default location of '.git', the .git/ folder (even for submodules) #", "ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are set up,", "ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After", "\"\"\" Invoke configuration for Golden Gate \"\"\" # First check that we are", "# Initialize constants that are common among all platforms/products def initialize_constants(cfg): cfg.C =", "among all platforms/products def initialize_constants(cfg): cfg.C = {} # We can't access the", "== 3 and sys.version_info.minor >= 5: print( \"\"\"You are using 'invoke' in a", "cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config", "\"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\")", "ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are set up, set the config.", "Inc # SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden Gate \"\"\" # First", "{} # We can't access the paths variable by using dot notation, since", "We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR,", "use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR", "Copyright 2017-2020 Fitbit, Inc # SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden Gate", "Imports import os import subprocess from invoke import Collection, Config, task from .", "Thus, find the folder .git/ is within and assume that's the root GIT_DIR", ". import android from . import apple from . import pylon from .", "import native from . import clean from . import wasm from . import", "subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants that are common", "First check that we are running in a Python >= 3.5 environment from", "check the 'Getting Started' guide for more details on how to setup your", "can't access the paths variable by using dot notation, since there is a", "Python >= 3.5 environment from __future__ import print_function import sys if not sys.version_info.major", "on a Config object. We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR =", "function # on a Config object. We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config", "much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\")", ". import pylon from . import native from . import clean from .", "cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR", "os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR)", "at the root of the repo. Thus, find the folder .git/ is within", "the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize", "default location of '.git', the .git/ folder (even for submodules) # will be", "2.x environment, but Python >= 3.5 is required. You have probably not activated", "the repo. Thus, find the folder .git/ is within and assume that's the", "\"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\")", "from . import clean from . import wasm from . import doc from", "= ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR,", "= os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add", ". import apple from . import pylon from . import native from .", "the 'Getting Started' guide for more details on how to setup your environment\"\"\")", "a paths() function # on a Config object. We much use Dictionary syntax.", "print_function import sys if not sys.version_info.major == 3 and sys.version_info.minor >= 5: print(", "os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR,", "probably not activated the 'gg' conda environment, please check the 'Getting Started' guide", ">= 3.5 environment from __future__ import print_function import sys if not sys.version_info.major ==", "syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR,", "def initialize_constants(cfg): cfg.C = {} # We can't access the paths variable by", "= Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native)", "Assuming you haven't moved the default location of '.git', the .git/ folder (even", "'gg' conda environment, please check the 'Getting Started' guide for more details on", "in a Python 2.x environment, but Python >= 3.5 is required. You have", "find the folder .git/ is within and assume that's the root GIT_DIR =", "ROOT_DIR = GIT_DIR # Initialize constants that are common among all platforms/products def", "that are common among all platforms/products def initialize_constants(cfg): cfg.C = {} # We", "platforms/products def initialize_constants(cfg): cfg.C = {} # We can't access the paths variable", "since there is a paths() function # on a Config object. We much", "\"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\")", "Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker)", "= os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR =", "collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) #", "Python 2.x environment, but Python >= 3.5 is required. You have probably not", "wasm from . import doc from . import docker # Assuming you haven't", "folder .git/ is within and assume that's the root GIT_DIR = subprocess.check_output(\"git rev-parse", "GIT_DIR # Initialize constants that are common among all platforms/products def initialize_constants(cfg): cfg.C", "ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are set up, set", "in a Python >= 3.5 environment from __future__ import print_function import sys if", "required. You have probably not activated the 'gg' conda environment, please check the", "environment, but Python >= 3.5 is required. You have probably not activated the", "setup your environment\"\"\") sys.exit(1) # Imports import os import subprocess from invoke import", "sys.version_info.minor >= 5: print( \"\"\"You are using 'invoke' in a Python 2.x environment,", "within and assume that's the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR", "= GIT_DIR # Initialize constants that are common among all platforms/products def initialize_constants(cfg):", "cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns =", "doc from . import docker # Assuming you haven't moved the default location", "haven't moved the default location of '.git', the .git/ folder (even for submodules)", "variable by using dot notation, since there is a paths() function # on", "# http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\")", "Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections are", "a Python 2.x environment, but Python >= 3.5 is required. You have probably", "from . import android from . import apple from . import pylon from", "folder (even for submodules) # will be at the root of the repo.", "conda environment, please check the 'Getting Started' guide for more details on how", "activated the 'gg' conda environment, please check the 'Getting Started' guide for more", "using dot notation, since there is a paths() function # on a Config", "from . import doc from . import docker # Assuming you haven't moved", ". import doc from . import docker # Assuming you haven't moved the", "object. We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR =", "for more details on how to setup your environment\"\"\") sys.exit(1) # Imports import", "import apple from . import pylon from . import native from . import", "initialize_constants(cfg): cfg.C = {} # We can't access the paths variable by using", "'Getting Started' guide for more details on how to setup your environment\"\"\") sys.exit(1)", "\"\"\" # First check that we are running in a Python >= 3.5", "'.git', the .git/ folder (even for submodules) # will be at the root", "environment, please check the 'Getting Started' guide for more details on how to", "import pylon from . import native from . import clean from . import", "notation, since there is a paths() function # on a Config object. We", "the .git/ folder (even for submodules) # will be at the root of", "\"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\")", "= os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config =", "cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE", "running in a Python >= 3.5 environment from __future__ import print_function import sys", "Initialize constants that are common among all platforms/products def initialize_constants(cfg): cfg.C = {}", "have probably not activated the 'gg' conda environment, please check the 'Getting Started'", "subprocess from invoke import Collection, Config, task from . import android from .", "are common among all platforms/products def initialize_constants(cfg): cfg.C = {} # We can't", "os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR,", "= os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR =", "cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR", "= os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\") cfg.C.APPS_DIR = os.path.join(cfg.C.BUILD_DIR_NATIVE, \"apps\") cfg.C.APPLE_BUILD_TEMP_DIR =", "SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden Gate \"\"\" # First check that", "__future__ import print_function import sys if not sys.version_info.major == 3 and sys.version_info.minor >=", "apple from . import pylon from . import native from . import clean", "Started' guide for more details on how to setup your environment\"\"\") sys.exit(1) #", "sys.version_info.major == 3 and sys.version_info.minor >= 5: print( \"\"\"You are using 'invoke' in", "# on a Config object. We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR", "Apache-2.0 \"\"\" Invoke configuration for Golden Gate \"\"\" # First check that we", "# Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc)", "docker # Assuming you haven't moved the default location of '.git', the .git/", "common among all platforms/products def initialize_constants(cfg): cfg.C = {} # We can't access", "import subprocess from invoke import Collection, Config, task from . import android from", "cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) #", "rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants that are common among", "constants that are common among all platforms/products def initialize_constants(cfg): cfg.C = {} #", "initialize_constants(config) # Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm)", "you haven't moved the default location of '.git', the .git/ folder (even for", "root of the repo. Thus, find the folder .git/ is within and assume", "sys.exit(1) # Imports import os import subprocess from invoke import Collection, Config, task", ".git/ folder (even for submodules) # will be at the root of the", "= subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants that are", "import print_function import sys if not sys.version_info.major == 3 and sys.version_info.minor >= 5:", "# Assuming you haven't moved the default location of '.git', the .git/ folder", "from invoke import Collection, Config, task from . import android from . import", "check that we are running in a Python >= 3.5 environment from __future__", "from . import wasm from . import doc from . import docker #", "ns.add_collection(docker) # After collections are set up, set the config. ns.configure(config) ns.configure(android.config) ns.configure(apple.config)", "root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants", "repo. Thus, find the folder .git/ is within and assume that's the root", "invoke import Collection, Config, task from . import android from . import apple", "import Collection, Config, task from . import android from . import apple from", "shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants that are common among all platforms/products", "Fitbit, Inc # SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden Gate \"\"\" #", "# SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden Gate \"\"\" # First check", "from __future__ import print_function import sys if not sys.version_info.major == 3 and sys.version_info.minor", "the paths variable by using dot notation, since there is a paths() function", "more details on how to setup your environment\"\"\") sys.exit(1) # Imports import os", "Python >= 3.5 is required. You have probably not activated the 'gg' conda", "\"apps\") cfg.C.APPLE_BUILD_TEMP_DIR = os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config)", "# We can't access the paths variable by using dot notation, since there", "environment from __future__ import print_function import sys if not sys.version_info.major == 3 and", ". import wasm from . import doc from . import docker # Assuming", "Collection, Config, task from . import android from . import apple from .", "2017-2020 Fitbit, Inc # SPDX-License-Identifier: Apache-2.0 \"\"\" Invoke configuration for Golden Gate \"\"\"", "a Python >= 3.5 environment from __future__ import print_function import sys if not", "on how to setup your environment\"\"\") sys.exit(1) # Imports import os import subprocess", "3.5 environment from __future__ import print_function import sys if not sys.version_info.major == 3", "= os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE =", "not activated the 'gg' conda environment, please check the 'Getting Started' guide for", "by using dot notation, since there is a paths() function # on a", "clean from . import wasm from . import doc from . import docker", "are using 'invoke' in a Python 2.x environment, but Python >= 3.5 is", ". import clean from . import wasm from . import doc from .", "os.path.join(cfg.C.PLATFORM_DIR, \"apple/output\") cfg.C.DOC_DIR = os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections", "import wasm from . import doc from . import docker # Assuming you", "import os import subprocess from invoke import Collection, Config, task from . import", "and sys.version_info.minor >= 5: print( \"\"\"You are using 'invoke' in a Python 2.x", "the default location of '.git', the .git/ folder (even for submodules) # will", "cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR =", "all platforms/products def initialize_constants(cfg): cfg.C = {} # We can't access the paths", "import android from . import apple from . import pylon from . import", "os.path.join(cfg.C.ROOT_DIR, \"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR,", "# First check that we are running in a Python >= 3.5 environment", "assume that's the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR", "GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR # Initialize constants that", "ns.add_collection(doc) ns.add_collection(docker) # After collections are set up, set the config. ns.configure(config) ns.configure(android.config)", "we are running in a Python >= 3.5 environment from __future__ import print_function", "sys if not sys.version_info.major == 3 and sys.version_info.minor >= 5: print( \"\"\"You are", "for submodules) # will be at the root of the repo. Thus, find", ". import docker # Assuming you haven't moved the default location of '.git',", "(even for submodules) # will be at the root of the repo. Thus,", "details on how to setup your environment\"\"\") sys.exit(1) # Imports import os import", "the folder .git/ is within and assume that's the root GIT_DIR = subprocess.check_output(\"git", "but Python >= 3.5 is required. You have probably not activated the 'gg'", "import docker # Assuming you haven't moved the default location of '.git', the", "import sys if not sys.version_info.major == 3 and sys.version_info.minor >= 5: print( \"\"\"You", "how to setup your environment\"\"\") sys.exit(1) # Imports import os import subprocess from", "\"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns = Collection() ns.add_collection(android) ns.add_collection(apple)", "that's the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\", shell=True).strip().decode(\"utf-8\") ROOT_DIR = GIT_DIR #", "os import subprocess from invoke import Collection, Config, task from . import android", "please check the 'Getting Started' guide for more details on how to setup", "import doc from . import docker # Assuming you haven't moved the default", "# will be at the root of the repo. Thus, find the folder", "a Config object. We much use Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR", "from . import apple from . import pylon from . import native from", "= os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns = Collection()", "\"xp/build\") cfg.C.BUILD_DIR = os.path.join(cfg.C.ROOT_DIR, \"xp/build/cmake\") cfg.C.BUILD_DIR_NATIVE = os.path.join(cfg.C.BUILD_DIR, \"native\") cfg.C.PLATFORM_DIR = os.path.join(cfg.C.ROOT_DIR, \"platform\")", "pylon from . import native from . import clean from . import wasm", "there is a paths() function # on a Config object. We much use", "Dictionary syntax. # http://docs.pyinvoke.org/en/0.15.0/api/config.html#module-invoke.config cfg.C.ROOT_DIR = ROOT_DIR cfg.C.BIN_DIR = os.path.join(cfg.C.ROOT_DIR, \"bin\") cfg.C.BUILD_ROOT_DIR =", "cfg.C = {} # We can't access the paths variable by using dot", ">= 5: print( \"\"\"You are using 'invoke' in a Python 2.x environment, but", "the root of the repo. Thus, find the folder .git/ is within and", "3 and sys.version_info.minor >= 5: print( \"\"\"You are using 'invoke' in a Python", "of the repo. Thus, find the folder .git/ is within and assume that's", "task from . import android from . import apple from . import pylon", "os.path.join(cfg.C.ROOT_DIR, \"docs\") config = Config(project_location=ROOT_DIR) initialize_constants(config) # Add collections ns = Collection() ns.add_collection(android)", "You have probably not activated the 'gg' conda environment, please check the 'Getting", "location of '.git', the .git/ folder (even for submodules) # will be at", ".git/ is within and assume that's the root GIT_DIR = subprocess.check_output(\"git rev-parse --show-toplevel\",", "Invoke configuration for Golden Gate \"\"\" # First check that we are running", "paths() function # on a Config object. We much use Dictionary syntax. #", "Golden Gate \"\"\" # First check that we are running in a Python", "= Collection() ns.add_collection(android) ns.add_collection(apple) ns.add_collection(pylon) ns.add_collection(native) ns.add_collection(clean) ns.add_collection(wasm) ns.add_collection(doc) ns.add_collection(docker) # After collections", "'invoke' in a Python 2.x environment, but Python >= 3.5 is required. You" ]
[ "\"static\") static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self,", "= get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type,", "\"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type =", "= ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name')", "callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "\"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs):", "= ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config) def", "\"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs):", "ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text =", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet =", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code", "arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback =", "return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback)", "interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto", "ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto", "self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet =", "ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self,", "= ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp =", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\")", "= ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text =", "= ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text =", "return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config) def", "callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip,", "callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code", "= kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated", "= ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config) def", "= ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback',", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "= ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback',", "interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text", "kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code", "\"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return", "def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "= kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated", "= ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def", "= kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback)", "interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text", "\"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\")", "= ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel", "return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text =", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback =", "\"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp,", "\"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self,", "ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self,", "= kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated", "callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry =", "interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto", "ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback',", "generated class. \"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto", "kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\")", "= kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback)", "ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self,", "= ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text =", "ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text =", "config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\")", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback", "get_arp = ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output,", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age =", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename')", "kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code", "get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\")", "hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "= ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback',", "= kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback)", "ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text =", "kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code", "ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address')", "ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback',", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text", "ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config)", "ET class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback')", "ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet')", "def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return", "brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self,", "config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic =", "ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text =", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def", "= ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry,", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved =", "return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "= get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type,", "callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "= ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def", "get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto", "input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic", "is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config)", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value')", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key =", "Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry =", "= ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address')", "callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text", "\"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address')", "ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback)", "mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config)", "ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self,", "ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback',", "get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config)", "= ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved')", "= ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\")", "\"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type =", "ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback)", "config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\")", "ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet')", "ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\")", "= ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static =", "\"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs):", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key =", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "= ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text =", "ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self,", "\"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type", "return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "**kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config =", "TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config)", "input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback", "= ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype,", "input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet =", "ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback)", "ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback =", "ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address", "return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "= ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text =", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self,", "static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs):", "\"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp')", "def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "\"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs):", "ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name')", "hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "\"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return", "get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\")", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel =", "callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto", "get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\")", "return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "= ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback',", "ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated", "kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code", "hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "\"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback", "= kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated", "ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype,", "ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback", "= ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text", "= ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address =", "arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto", "\"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs):", "interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text", "ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\")", "\"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\")", "\"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback =", "ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self,", "callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static", "\"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs):", "= ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def", "get_arp = ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input,", "ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\")", "arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config)", "\"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback =", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key", "get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\")", "get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "= ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry,", "GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto", "arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto", "= ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback',", "\"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs):", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name", "self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp", "\"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text", "kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return", "ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self,", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"input\") input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\")", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "= ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config) def", "kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code", "return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\")", "ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet", "ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static,", "= ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry,", "= ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name =", "TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto", "arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype =", "\"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\")", "ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated", "ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback)", "ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet", "config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static =", "= kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated", "kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self,", "= get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry,", "self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\")", "HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback',", "Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder,", "interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto", "ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self,", "**kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\")", "= kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet,", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name", "interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text", "def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "\"input\") input_type = ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\")", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "= ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type =", "ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config)", "get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet =", "self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet =", "xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename", "interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text", "= ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text =", "hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "= ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto", "def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text", "= kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve,", "interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback =", "class. \"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "\"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\")", "callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\")", "= get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type,", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet", "ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self,", "ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback',", "self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "= ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry,", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\")", "= ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text =", "ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback", "= ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type')", "def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs):", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve =", "as ET class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs): self._callback =", "\"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return", "xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet,", "\"input-type\") static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback)", "ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback',", "interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config)", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self,", "GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config)", "callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "= kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback)", "ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self,", "ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text =", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype,", "= ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config) def", "return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") static", "= ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry,", "ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self,", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve =", "= ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def", "= kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated", "kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return", "= kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated", "= kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback)", "ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic,", "\"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs):", "ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\")", "callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\")", "\"input\") input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\")", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address')", "get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "= ET.SubElement(input, \"input-type\") static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback =", "= ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age')", "\"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback =", "dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback", "\"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback =", "\"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs):", "= kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet,", "callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "\"static\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code", "Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback =", "callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address =", "self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp input", "xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value", "config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip =", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address", "get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text", "= ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def", "Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback =", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet", "ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback)", "self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "= kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback)", "interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config)", "mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet", "= ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved", "static = ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\")", "__init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "= ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry,", "Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config)", "get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\")", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet", "ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback',", "def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback =", "python import xml.etree.ElementTree as ET class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self,", "\"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\")", "hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max =", "\"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs):", "= ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback',", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "\"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs):", "= kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated", "def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel =", "ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback',", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback',", "callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "= ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry", "\"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return", "= kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated", "ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text =", "def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "= kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated", "arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value =", "= get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type,", "get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\")", "return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "= ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback',", "interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback =", "\"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs):", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback',", "\"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback", "= ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config) def", "TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback =", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config) def", "\"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "\"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp,", "\"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs):", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype,", "ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel')", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback", "ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type')", "= kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated", "def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "= kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated", "\"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return", "def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp output =", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype,", "= ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text =", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet =", "= ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text =", "= kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated", "ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet')", "= ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return callback(config)", "kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "= kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Port_channel = ET.SubElement(interfacetype, \"Port-channel\") Port_channel = ET.SubElement(Port_channel,", "ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type =", "def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "xml.etree.ElementTree as ET class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs): self._callback", "\"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet", "get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self,", "= kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated", "output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text", "= kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "Port_channel = ET.SubElement(Port_channel, \"Port-channel\") Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config)", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback =", "def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback)", "ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address')", "hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "= kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated", "ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\")", "= ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def", "entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto", "callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "= kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated", "= ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config) def", "arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet =", "hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "import xml.etree.ElementTree as ET class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs):", "return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve')", "return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "= ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config)", "is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry,", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') is_resolved = ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text", "ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback = kwargs.pop('callback', self._callback)", "def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "\"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback =", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry,", "def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "\"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs):", "ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback)", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\")", "ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\")", "kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "= ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback',", "ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback',", "ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface,", "return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "\"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback =", "def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config,", "\"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback", "= ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text", "= ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address =", "FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config)", "xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback", "ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max,", "= kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated", "callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "= ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry,", "ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip", "callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text", "= ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback',", "kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\")", "ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback)", "= get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry,", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "\"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return", "#!/usr/bin/env python import xml.etree.ElementTree as ET class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def", "self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "**kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "\"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs):", "kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code", "\"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs):", "get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code", "input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text", "ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback", "ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text =", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\")", "kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code", "\"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs):", "= kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto Generated", "config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface =", "kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\")", "kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code", "Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto", "ET.Element(\"get_arp\") config = get_arp input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface", "\"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return", "ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\")", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "= ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config) def", "\"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address')", "config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address =", "\"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback)", "return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp input =", "ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self,", "self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback)", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code", "\"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") system_max", "ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet')", "interface_name = ET.SubElement(interface, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config)", "= kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback)", "callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto", "kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\")", "= ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback',", "ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback)", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") GigabitEthernet =", "HundredGigabitEthernet = ET.SubElement(interfacetype, \"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback =", "= kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") TenGigabitEthernet = ET.SubElement(interfacetype, \"TenGigabitEthernet\") TenGigabitEthernet = ET.SubElement(TenGigabitEthernet,", "= ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text =", "callback(config) def get_arp_input_input_type_interface_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp =", "hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "= ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type')", "= kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated", "Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder,", "interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config)", "kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs): \"\"\"Auto Generated Code", "\"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve = ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback", "def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "ET.SubElement(arp_entry, \"is-resolved\") is_resolved.text = kwargs.pop('is_resolved') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_age(self,", "= ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry,", "= kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age", "input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback", "self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype, \"Ve\") Ve", "\"interfacetype\") FortyGigabitEthernet = ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp output", "get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self,", "= ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config) def", "class brocade_arp(object): \"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def", "arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text = kwargs.pop('arp_ip_address') callback = kwargs.pop('callback', self._callback) return callback(config)", "ET.SubElement(input_type, \"static\") static = ET.SubElement(static, \"static\") callback = kwargs.pop('callback', self._callback) return callback(config) def", "arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text =", "entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return callback(config)", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "\"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config = get_arp", "return callback(config) def get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text =", "return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_mac_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface,", "kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return", "FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): \"\"\"Auto", "def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\")", "kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code", "ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self,", "self._callback) return callback(config) def get_arp_output_arp_entry_is_resolved(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "kwargs.pop('ip_address') mac_address = ET.SubElement(arp_entry, \"mac-address\") mac_address.text = kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('ip_address') entry_type = ET.SubElement(arp_entry, \"entry-type\") entry_type.text = kwargs.pop('entry_type') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_arp_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype", "\"interface-name\") interface_name.text = kwargs.pop('interface_name') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs):", "callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder =", "return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder", "\"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback', self._callback) return", "self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacename(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "input = ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address", "= ET.SubElement(input, \"input-type\") ip = ET.SubElement(input_type, \"ip\") ip_address = ET.SubElement(ip, \"ip-address\") ip_address.text =", "= ET.SubElement(ip, \"ip-address\") ip_address.text = kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\",", "arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename =", "return callback(config) def get_arp_input_input_type_interface_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address = ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address.text =", "kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_dynamic_dynamic(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config)", "\"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback =", "= kwargs.pop('arp_ip_address') interfacename = ET.SubElement(arp_entry, \"interfacename\") interfacename.text = kwargs.pop('interfacename') callback = kwargs.pop('callback', self._callback)", "arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name =", "callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): \"\"\"Auto Generated Code \"\"\"", "kwargs.pop('ip_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_ip_address(self, **kwargs): \"\"\"Auto Generated Code", "\"interface-type\") interface_type.text = kwargs.pop('interface_type') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs):", "ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_name = ET.SubElement(arp_entry, \"interface-name\")", "\"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') age = ET.SubElement(arp_entry, \"age\") age.text", "\"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_entry_type(self, **kwargs):", "= ET.Element(\"get_arp\") config = get_arp output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\")", "self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "\"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address_key = ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') mac_address", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_system_max_arp(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "self._callback) return callback(config) def get_arp_output_arp_entry_interface_name(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "= ET.SubElement(TenGigabitEthernet, \"TenGigabitEthernet\") TenGigabitEthernet.text = kwargs.pop('TenGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config) def", "= ET.SubElement(get_arp, \"input\") input_type = ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic =", "= ET.SubElement(dynamic, \"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto", "\"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_name = ET.SubElement(interface, \"interface-name\")", "GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback =", "kwargs.pop('mac_address') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_output_arp_entry_interface_type(self, **kwargs): \"\"\"Auto Generated Code", "= ET.SubElement(arp_entry, \"arp-ip-address\") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, \"interfacetype\") Ve = ET.SubElement(interfacetype,", "= ET.SubElement(interfacetype, \"FortyGigabitEthernet\") FortyGigabitEthernet = ET.SubElement(FortyGigabitEthernet, \"FortyGigabitEthernet\") FortyGigabitEthernet.text = kwargs.pop('FortyGigabitEthernet') callback = kwargs.pop('callback',", "\"input\") input_type = ET.SubElement(input, \"input-type\") interface = ET.SubElement(input_type, \"interface\") interface_type = ET.SubElement(interface, \"interface-type\")", "\"interfacetype\") GigabitEthernet = ET.SubElement(interfacetype, \"GigabitEthernet\") GigabitEthernet = ET.SubElement(GigabitEthernet, \"GigabitEthernet\") GigabitEthernet.text = kwargs.pop('GigabitEthernet') callback", "mac_address_value = ET.SubElement(arp_entry, \"mac-address-value\") mac_address_value.text = kwargs.pop('mac_address_value') callback = kwargs.pop('callback', self._callback) return callback(config)", "\"HundredGigabitEthernet\") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, \"HundredGigabitEthernet\") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return", "kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config =", "output = ET.SubElement(get_arp, \"output\") arp_entry = ET.SubElement(output, \"arp-entry\") ip_address = ET.SubElement(arp_entry, \"ip-address\") ip_address.text", "get_arp_output_arp_entry_age(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp = ET.Element(\"get_arp\") config", "Port_channel.text = kwargs.pop('Port_channel') callback = kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_GigabitEthernet_GigabitEthernet(self, **kwargs): \"\"\"Auto", "return callback(config) def get_arp_input_input_type_ip_ip_address(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\") get_arp", "age = ET.SubElement(arp_entry, \"age\") age.text = kwargs.pop('age') callback = kwargs.pop('callback', self._callback) return callback(config)", "ET.SubElement(arp_entry, \"ip-address\") ip_address_key.text = kwargs.pop('ip_address') interface_type = ET.SubElement(arp_entry, \"interface-type\") interface_type.text = kwargs.pop('interface_type') callback", "ET.SubElement(Ve, \"Ve\") Ve.text = kwargs.pop('Ve') callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_interface_interface_type(self,", "\"\"\"Auto generated class. \"\"\" def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def hide_arp_holder_system_max_arp(self, **kwargs):", "= ET.SubElement(input, \"input-type\") dynamic = ET.SubElement(input_type, \"dynamic\") dynamic = ET.SubElement(dynamic, \"dynamic\") callback =", "system_max = ET.SubElement(hide_arp_holder, \"system-max\") arp = ET.SubElement(system_max, \"arp\") arp.text = kwargs.pop('arp') callback =", "\"dynamic\") callback = kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code", "ET.Element(\"config\") hide_arp_holder = ET.SubElement(config, \"hide-arp-holder\", xmlns=\"urn:brocade.com:mgmt:brocade-arp\") arp_entry = ET.SubElement(hide_arp_holder, \"arp-entry\") arp_ip_address_key = ET.SubElement(arp_entry,", "self._callback) return callback(config) def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config = ET.Element(\"config\")", "= kwargs.pop('callback', self._callback) return callback(config) def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config", "= kwargs.pop('callback', self._callback) return callback(config) def get_arp_input_input_type_static_static(self, **kwargs): \"\"\"Auto Generated Code \"\"\" config" ]
[ "\"Error: Should be a positive number\" if year % 100 == 0: if", "Should be a integer\" if year < 0: return \"Error: Should be a", "== 0: if year % 400 == 0: return 'Is leap year' else:", "== 0: return 'Is leap year' else: return 'Is not leap year' elif", "0: return 'Is leap year' else: return 'Is not leap year' elif year", "return 'Is not leap year' elif year % 4 == 0: return 'Is", "positive number\" if year % 100 == 0: if year % 400 ==", "not leap year' elif year % 4 == 0: return 'Is leap year'", "a positive number\" if year % 100 == 0: if year % 400", "400 == 0: return 'Is leap year' else: return 'Is not leap year'", "100 == 0: if year % 400 == 0: return 'Is leap year'", "\"Error: Should be a integer\" if year < 0: return \"Error: Should be", "% 400 == 0: return 'Is leap year' else: return 'Is not leap", "if not isinstance(year, int): return \"Error: Should be a integer\" if year <", "% 4 == 0: return 'Is leap year' else: return 'Is not leap", "'Is not leap year' elif year % 4 == 0: return 'Is leap", "else: return 'Is not leap year' elif year % 4 == 0: return", "a integer\" if year < 0: return \"Error: Should be a positive number\"", "if year < 0: return \"Error: Should be a positive number\" if year", "year < 0: return \"Error: Should be a positive number\" if year %", "return 'Is leap year' else: return 'Is not leap year' elif year %", "integer\" if year < 0: return \"Error: Should be a positive number\" if", "0: return \"Error: Should be a positive number\" if year % 100 ==", "return \"Error: Should be a positive number\" if year % 100 == 0:", "if year % 100 == 0: if year % 400 == 0: return", "year' elif year % 4 == 0: return 'Is leap year' else: return", "elif year % 4 == 0: return 'Is leap year' else: return 'Is", "return \"Error: Should be a integer\" if year < 0: return \"Error: Should", "% 100 == 0: if year % 400 == 0: return 'Is leap", "def es_bisiesto(year): if not isinstance(year, int): return \"Error: Should be a integer\" if", "int): return \"Error: Should be a integer\" if year < 0: return \"Error:", "es_bisiesto(year): if not isinstance(year, int): return \"Error: Should be a integer\" if year", "'Is leap year' else: return 'Is not leap year' elif year % 4", "year % 400 == 0: return 'Is leap year' else: return 'Is not", "4 == 0: return 'Is leap year' else: return 'Is not leap year'", "year' else: return 'Is not leap year' elif year % 4 == 0:", "< 0: return \"Error: Should be a positive number\" if year % 100", "number\" if year % 100 == 0: if year % 400 == 0:", "be a integer\" if year < 0: return \"Error: Should be a positive", "be a positive number\" if year % 100 == 0: if year %", "Should be a positive number\" if year % 100 == 0: if year", "leap year' elif year % 4 == 0: return 'Is leap year' else:", "leap year' else: return 'Is not leap year' elif year % 4 ==", "year % 4 == 0: return 'Is leap year' else: return 'Is not", "isinstance(year, int): return \"Error: Should be a integer\" if year < 0: return", "if year % 400 == 0: return 'Is leap year' else: return 'Is", "not isinstance(year, int): return \"Error: Should be a integer\" if year < 0:", "0: if year % 400 == 0: return 'Is leap year' else: return", "year % 100 == 0: if year % 400 == 0: return 'Is" ]
[ "in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command()", "functools class utility: def __init__(self, bot): self.bot = bot @commands.command() async def avatar(self,", "member: discord.Member = None): if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a", "hello(self, ctx): \"\"\"*hello A command that will respond with a random greeting. \"\"\"", "@commands.command(name='members') async def membs(self, ctx): server = ctx.guild for member in server.members: await", "\"\"\"Write text in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") +", "from discord.ext import commands import aiohttp import sys import time import googletrans import", "ctx.guild for member in server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server", "= str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server", "async def rol(self, ctx): server = ctx.guild list = [] for role in", "discord.Embed(name = 'Roles', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async", "ctx): \"\"\"*hello A command that will respond with a random greeting. \"\"\" choices", "await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command()", "async def avatar(self, ctx, *, member: discord.Member = None): if member is None:", "discord from discord.ext import commands import aiohttp import sys import time import googletrans", "ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command() async def echo(self, ctx,", "commands import aiohttp import sys import time import googletrans import functools class utility:", "def rol(self, ctx): server = ctx.guild list = [] for role in server.roles:", "discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self, ctx, *,", "command that will respond with a random greeting. \"\"\" choices = ('Hey!', 'Hello!',", "list.append(role.name) embed = discord.Embed(name = 'Roles', description = str(list) ,colour = discord.Colour.green()) await", "server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server = ctx.guild for role", "import sys import time import googletrans import functools class utility: def __init__(self, bot):", "server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server = ctx.guild list =", "def avatar(self, ctx, *, member: discord.Member = None): if member is None: embed=discord.Embed(title=\"No", "color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self, ctx, *, msg): \"\"\"Write text", "ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server = ctx.guild list = [] for", "self.bot = bot @commands.command() async def avatar(self, ctx, *, member: discord.Member = None):", "sys.platform) @commands.command(name='members') async def membs(self, ctx): server = ctx.guild for member in server.members:", "await ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello A command that will respond", "googletrans import functools class utility: def __init__(self, bot): self.bot = bot @commands.command() async", "bot): self.bot = bot @commands.command() async def avatar(self, ctx, *, member: discord.Member =", "= discord.Embed(name = 'Roles', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme')", "@commands.command() async def echo(self, ctx, *, content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async", "'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on", "= ctx.guild for role in server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self, ctx):", "will respond with a random greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!',", "= None): if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to", "random greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices))", "= 'Roles', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def", "ctx, *, member: discord.Member = None): if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please", "def plat(self,ctx): await ctx.send('Running on ' + sys.platform) @commands.command(name='members') async def membs(self, ctx):", "ctx.guild list = [] for role in server.roles: list.append(role.name) embed = discord.Embed(name =", "'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on ' +", "+ sys.platform) @commands.command(name='members') async def membs(self, ctx): server = ctx.guild for member in", "+ \"```\") @commands.command() async def echo(self, ctx, *, content:str): await ctx.send(content) await ctx.message.delete()", "ctx): server = ctx.guild list = [] for member in server.members: list.append(member.name) embed", "discord.Member = None): if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user", "on ' + sys.platform) @commands.command(name='members') async def membs(self, ctx): server = ctx.guild for", "picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self, ctx, *, msg): \"\"\"Write", "description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self, ctx):", "format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command() async def", "ctx): server = ctx.guild list = [] for role in server.roles: list.append(role.name) embed", "import aiohttp import sys import time import googletrans import functools class utility: def", "ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello A command that will", "role in server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles', description = str(list) ,colour", "def mem(self, ctx): server = ctx.guild list = [] for member in server.members:", "member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to view his profile!\",", "ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello A command that will respond with", "for member in server.members: list.append(member.name) embed = discord.Embed(name = 'Members', description = str(list)", "await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on ' + sys.platform) @commands.command(name='members')", "= discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server = ctx.guild list", "def __init__(self, bot): self.bot = bot @commands.command() async def avatar(self, ctx, *, member:", "ctx, *, msg): \"\"\"Write text in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" +", "rols(self, ctx): server = ctx.guild for role in server.roles: await ctx.send(role) @commands.command(name='member') async", "await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command() async def echo(self,", "discord.ext import commands import aiohttp import sys import time import googletrans import functools", "his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url)", "@commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on ' + sys.platform) @commands.command(name='members') async def", "= 'Members', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def", "in server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server = ctx.guild for", "if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to view his", "user to view his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile", "('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await", "None): if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to view", ",colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server = ctx.guild", "= ctx.guild list = [] for member in server.members: list.append(member.name) embed = discord.Embed(name", "A command that will respond with a random greeting. \"\"\" choices = ('Hey!',", "async def code(self, ctx, *, msg): \"\"\"Write text in code format.\"\"\" await ctx.message.delete()", "= [] for member in server.members: list.append(member.name) embed = discord.Embed(name = 'Members', description", "\"```\") @commands.command() async def echo(self, ctx, *, content:str): await ctx.send(content) await ctx.message.delete() @commands.command()", "ctx.send('Running on ' + sys.platform) @commands.command(name='members') async def membs(self, ctx): server = ctx.guild", "= ctx.guild list = [] for role in server.roles: list.append(role.name) embed = discord.Embed(name", "that will respond with a random greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!',", "role in server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server = ctx.guild", "import functools class utility: def __init__(self, bot): self.bot = bot @commands.command() async def", "echo(self, ctx, *, content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self, ctx):", "class utility: def __init__(self, bot): self.bot = bot @commands.command() async def avatar(self, ctx,", "await ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server = ctx.guild list = []", "ctx, *, content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello", "async def plat(self,ctx): await ctx.send('Running on ' + sys.platform) @commands.command(name='members') async def membs(self,", "profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self, ctx, *, msg):", "discord.Embed(name = 'Members', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async", "description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx):", "__init__(self, bot): self.bot = bot @commands.command() async def avatar(self, ctx, *, member: discord.Member", "for role in server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles', description = str(list)", "async def rols(self, ctx): server = ctx.guild for role in server.roles: await ctx.send(role)", "profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await", "plat(self,ctx): await ctx.send('Running on ' + sys.platform) @commands.command(name='members') async def membs(self, ctx): server", "is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to view his profile!\", color=0xff0000)", "color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed)", "respond with a random greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!',", "[] for member in server.members: list.append(member.name) embed = discord.Embed(name = 'Members', description =", "' + sys.platform) @commands.command(name='members') async def membs(self, ctx): server = ctx.guild for member", "@commands.command() async def avatar(self, ctx, *, member: discord.Member = None): if member is", "sys import time import googletrans import functools class utility: def __init__(self, bot): self.bot", "ctx.guild list = [] for member in server.members: list.append(member.name) embed = discord.Embed(name =", "list = [] for role in server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles',", "bot @commands.command() async def avatar(self, ctx, *, member: discord.Member = None): if member", "content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello A command", "membs(self, ctx): server = ctx.guild for member in server.members: await ctx.send(member) @commands.command(name='roles') async", "'Roles', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self,", "import time import googletrans import functools class utility: def __init__(self, bot): self.bot =", "async def mem(self, ctx): server = ctx.guild list = [] for member in", "discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server = ctx.guild list =", "str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self, ctx): await ctx.send(ctx.author.mention)", ",colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self, ctx): await ctx.send(ctx.author.mention) def", "ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server = ctx.guild list = [] for", "text in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\")", "in server.members: list.append(member.name) embed = discord.Embed(name = 'Members', description = str(list) ,colour =", "a random greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await", "ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on ' + sys.platform) @commands.command(name='members') async", "avatar(self, ctx, *, member: discord.Member = None): if member is None: embed=discord.Embed(title=\"No mention!\",", "@commands.command(name='roles') async def rols(self, ctx): server = ctx.guild for role in server.roles: await", "mention a user to view his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed =", "view his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657)", "server.members: list.append(member.name) embed = discord.Embed(name = 'Members', description = str(list) ,colour = discord.Colour.green())", "member in server.members: list.append(member.name) embed = discord.Embed(name = 'Members', description = str(list) ,colour", "server = ctx.guild for member in server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self,", "list = [] for member in server.members: list.append(member.name) embed = discord.Embed(name = 'Members',", "[] for role in server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles', description =", "discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self, ctx): await ctx.send(ctx.author.mention) def setup(bot): bot.add_cog(utility(bot))", "= ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx):", "a user to view his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s", "import googletrans import functools class utility: def __init__(self, bot): self.bot = bot @commands.command()", "choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def", "= str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self, ctx): await", "description=\"Please mention a user to view his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed", "def rols(self, ctx): server = ctx.guild for role in server.roles: await ctx.send(role) @commands.command(name='member')", "greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform'])", "*, content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello A", "import discord from discord.ext import commands import aiohttp import sys import time import", "embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self, ctx, *, msg): \"\"\"Write text in", "msg): \"\"\"Write text in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\")", "for role in server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server =", "embed = discord.Embed(name = 'Roles', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed)", "mem(self, ctx): server = ctx.guild list = [] for member in server.members: list.append(member.name)", "list.append(member.name) embed = discord.Embed(name = 'Members', description = str(list) ,colour = discord.Colour.green()) await", "\"\") + \"```\") @commands.command() async def echo(self, ctx, *, content:str): await ctx.send(content) await", "'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on ' + sys.platform)", "'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running", "= ctx.guild for member in server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx):", "@commands.command() async def hello(self, ctx): \"\"\"*hello A command that will respond with a", "'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async def plat(self,ctx): await ctx.send('Running on '", "server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles', description = str(list) ,colour = discord.Colour.green())", "utility: def __init__(self, bot): self.bot = bot @commands.command() async def avatar(self, ctx, *,", "def echo(self, ctx, *, content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self,", "ctx): server = ctx.guild for role in server.roles: await ctx.send(role) @commands.command(name='member') async def", "for member in server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server =", "embed = discord.Embed(name = 'Members', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed)", "def membs(self, ctx): server = ctx.guild for member in server.members: await ctx.send(member) @commands.command(name='roles')", "str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server =", "msg.replace(\"`\", \"\") + \"```\") @commands.command() async def echo(self, ctx, *, content:str): await ctx.send(content)", "async def hello(self, ctx): \"\"\"*hello A command that will respond with a random", "ctx): server = ctx.guild for member in server.members: await ctx.send(member) @commands.command(name='roles') async def", "rol(self, ctx): server = ctx.guild list = [] for role in server.roles: list.append(role.name)", "None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to view his profile!\", color=0xff0000) await", "@commands.command(name='role') async def rol(self, ctx): server = ctx.guild list = [] for role", "= [] for role in server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles', description", "to view his profile!\", color=0xff0000) await ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\",", "member in server.members: await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server = ctx.guild", "= discord.Embed(name = 'Members', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role')", "with a random greeting. \"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!')", "ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command() async def echo(self, ctx, *, content:str):", "await ctx.send(embed=embed) @commands.command(name='role') async def rol(self, ctx): server = ctx.guild list = []", "ctx.send(embed=embed) else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async", "\"\"\"*hello A command that will respond with a random greeting. \"\"\" choices =", "server = ctx.guild for role in server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self,", "code(self, ctx, *, msg): \"\"\"Write text in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\"", "= discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='pingme') async def pingme(self, ctx): await ctx.send(ctx.author.mention) def setup(bot):", "await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command() async def echo(self, ctx, *,", "ctx.guild for role in server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server", "in server.roles: await ctx.send(role) @commands.command(name='member') async def mem(self, ctx): server = ctx.guild list", "import commands import aiohttp import sys import time import googletrans import functools class", "server = ctx.guild list = [] for member in server.members: list.append(member.name) embed =", "await ctx.send(embed=embed) @commands.command() async def code(self, ctx, *, msg): \"\"\"Write text in code", "async def echo(self, ctx, *, content:str): await ctx.send(content) await ctx.message.delete() @commands.command() async def", "else: embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def", "'Members', description = str(list) ,colour = discord.Colour.green()) await ctx.send(embed=embed) @commands.command(name='role') async def rol(self,", "embed=discord.Embed(title=\"No mention!\", description=\"Please mention a user to view his profile!\", color=0xff0000) await ctx.send(embed=embed)", "time import googletrans import functools class utility: def __init__(self, bot): self.bot = bot", "ctx.send(embed=embed) @commands.command() async def code(self, ctx, *, msg): \"\"\"Write text in code format.\"\"\"", "@commands.command(name='member') async def mem(self, ctx): server = ctx.guild list = [] for member", "= discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self, ctx,", "= bot @commands.command() async def avatar(self, ctx, *, member: discord.Member = None): if", "\"\"\" choices = ('Hey!', 'Hello!', 'Hi!', 'Hallo!', 'Bonjour!', 'Hola!') await ctx.send(choice(choices)) @commands.command(aliases=['platform']) async", "in server.roles: list.append(role.name) embed = discord.Embed(name = 'Roles', description = str(list) ,colour =", "@commands.command() async def code(self, ctx, *, msg): \"\"\"Write text in code format.\"\"\" await", "embed = discord.Embed(title=f\"{member}'s profile picture\", color=0xeee657) embed.set_image(url=member.avatar_url) await ctx.send(embed=embed) @commands.command() async def code(self,", "code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\", \"\") + \"```\") @commands.command() async", "+ msg.replace(\"`\", \"\") + \"```\") @commands.command() async def echo(self, ctx, *, content:str): await", "async def membs(self, ctx): server = ctx.guild for member in server.members: await ctx.send(member)", "*, member: discord.Member = None): if member is None: embed=discord.Embed(title=\"No mention!\", description=\"Please mention", "def hello(self, ctx): \"\"\"*hello A command that will respond with a random greeting.", "server = ctx.guild list = [] for role in server.roles: list.append(role.name) embed =", "def code(self, ctx, *, msg): \"\"\"Write text in code format.\"\"\" await ctx.message.delete() await", "ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server = ctx.guild for role in server.roles:", "await ctx.send(content) await ctx.message.delete() @commands.command() async def hello(self, ctx): \"\"\"*hello A command that", "await ctx.send('Running on ' + sys.platform) @commands.command(name='members') async def membs(self, ctx): server =", "aiohttp import sys import time import googletrans import functools class utility: def __init__(self,", "mention!\", description=\"Please mention a user to view his profile!\", color=0xff0000) await ctx.send(embed=embed) else:", "*, msg): \"\"\"Write text in code format.\"\"\" await ctx.message.delete() await ctx.send(\"```\" + msg.replace(\"`\",", "await ctx.send(member) @commands.command(name='roles') async def rols(self, ctx): server = ctx.guild for role in" ]
[ "598749: 2017, 598750: 2017, 598751: 2017, 598752: 2017, 598753: 2017, 598754: 2017, 598755:", "598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ', 598750: 'units", "598754: 2017, 598755: 2017, 598756: 2017, 598757: 2017, 598758: 2017, 598759: 2017, 598760:", "$5,000 and over', 598750: 'Persons with income of $10,000 and over', 598751: 'Persons", "'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year, Age, sex,", "'Persons with income of $100,000 and over', 598758: 'Persons with income of $150,000", "low_memory=False) age = \"35 to 44 years\" year = 2017 geo = \"Canada\"", "'units ', 598750: 'units ', 598751: 'units ', 598752: 'units ', 598753: 'units", "as np import pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def", "'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex':", "598752: 2017, 598753: 2017, 598754: 2017, 598755: 2017, 598756: 2017, 598757: 2017, 598758:", "years', 598758: '35 to 44 years', 598759: '35 to 44 years', 598760: '35", "'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load the", "'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752:", "with income of $150,000 and over', 598759: 'Persons with income of $200,000 and", "470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} # params path =", "193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\" df", "df = pd.read_csv(path, low_memory=False) # parameters year = 2017 Age = '25 to", "'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada',", "'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load the data", "and over', 598754: 'Persons with income of $35,000 and over', 598755: 'Persons with", "'Persons with income of $150,000 and over', 598759: 'Persons with income of $200,000", "598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755:", "\"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source',", "$100,000 and over', 598758: 'Persons with income of $150,000 and over', 598759: 'Persons", "income of $250,000 and over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017, 598751:", "to 44 years', 598755: '35 to 44 years', 598756: '35 to 44 years',", "df = subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total income\"], ['Median income (excluding", "$20,000 and over', 598753: 'Persons with income of $25,000 and over', 598754: 'Persons", "'35 to 44 years', 598752: '35 to 44 years', 598753: '35 to 44", "', 598757: 'units ', 598758: 'units ', 598759: 'units ', 598760: 'units '},", "44 years', 598756: '35 to 44 years', 598757: '35 to 44 years', 598758:", "44 years', 598758: '35 to 44 years', 598759: '35 to 44 years', 598760:", "subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35 to 44", "'Persons with income of $35,000 and over', 598755: 'Persons with income of $50,000", "= pd.read_csv(path, low_memory=False) # parameters year = 2017 Age = '25 to 34", "'Persons with income under $5,000', 598749: 'Persons with income of $5,000 and over',", "age = \"35 to 44 years\" year = 2017 geo = \"Canada\" sex", "( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35", "598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\"", "'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total", "years', 598749: '35 to 44 years', 598750: '35 to 44 years', 598751: '35", "sex = \"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group',", "598757: 'Persons with income of $100,000 and over', 598758: 'Persons with income of", "over', 598760: 'Persons with income of $250,000 and over'}, 'REF_DATE': {598748: 2017, 598749:", "598751: 'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females', 598757:", "', 598760: 'units '}, 'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females',", "under $5,000', 598749: 'Persons with income of $5,000 and over', 598750: 'Persons with", "numpy as np import pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo )", "'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017, 598751: 2017, 598752: 2017, 598753: 2017,", "'units '}, 'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females',", "= pd.read_csv(path, low_memory=False) age = \"35 to 44 years\" year = 2017 geo", "of $200,000 and over', 598760: 'Persons with income of $250,000 and over'}, 'REF_DATE':", "of $15,000 and over', 598752: 'Persons with income of $20,000 and over', 598753:", "to 44 years', 598757: '35 to 44 years', 598758: '35 to 44 years',", "$50,000 and over', 598756: 'Persons with income of $75,000 and over', 598757: 'Persons", "958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} # params", "2017, 598756: 2017, 598757: 2017, 598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748:", "2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ', 598750: 'units ',", "= \"Females\" df = subset_year_age_sex_geo(df, year, age, sex, geo) df = subset_plot_data_for_income_bins(df) assert", "'35 to 44 years', 598756: '35 to 44 years', 598757: '35 to 44", "group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year, Age,", "year, age, sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot():", "df, year, Age, sex, geo, [\"Total income\"], ['Median income (excluding zeros)'], cols_to_keep) assert", "'35 to 44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada',", "== df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25 to 34 years'},", "years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR':", "of $150,000 and over', 598759: 'Persons with income of $200,000 and over', 598760:", "$25,000 and over', 598754: 'Persons with income of $35,000 and over', 598755: 'Persons", "598759: '35 to 44 years', 598760: '35 to 44 years'}, 'GEO': {598748: 'Canada',", "2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'},", "598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ', 598750: 'units ', 598751:", "44 years', 598760: '35 to 44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750:", "from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age", "598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ',", "= 2017 Age = '25 to 34 years' sex = \"Females\" geo =", "$250,000 and over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017, 598751: 2017, 598752:", "params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age = \"35 to 44", "Age = '25 to 34 years' sex = \"Females\" geo = \"Canada\" cols_to_keep", "44 years\" year = 2017 geo = \"Canada\" sex = \"Females\" df =", "and over', 598750: 'Persons with income of $10,000 and over', 598751: 'Persons with", "of $35,000 and over', 598755: 'Persons with income of $50,000 and over', 598756:", "over', 598754: 'Persons with income of $35,000 and over', 598755: 'Persons with income", "to 44 years', 598756: '35 to 44 years', 598757: '35 to 44 years',", "expected_value = {'Age group': {1550629: '25 to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income", "\"35 to 44 years\" year = 2017 geo = \"Canada\" sex = \"Females\"", "598755: 'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE':", "'35 to 44 years', 598760: '35 to 44 years'}, 'GEO': {598748: 'Canada', 598749:", "2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0,", "def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35 to 44 years', 598749: '35", "'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income", "over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017, 598751: 2017, 598752: 2017, 598753:", "cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ]", "{1550629: '25 to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total income'},", "598749: 'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females', 598755:", "1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0,", "'Persons with income of $20,000 and over', 598753: 'Persons with income of $25,000", "test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25 to 34 years'}, 'GEO': {1550629: 'Canada'},", "', 598750: 'units ', 598751: 'units ', 598752: 'units ', 598753: 'units ',", "over', 598757: 'Persons with income of $100,000 and over', 598758: 'Persons with income", "income of $150,000 and over', 598759: 'Persons with income of $200,000 and over',", "test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35 to 44 years', 598749: '35 to", "{598748: 'Persons with income under $5,000', 598749: 'Persons with income of $5,000 and", "with income of $100,000 and over', 598758: 'Persons with income of $150,000 and", "with income of $25,000 and over', 598754: 'Persons with income of $35,000 and", "and over', 598759: 'Persons with income of $200,000 and over', 598760: 'Persons with", "= '25 to 34 years' sex = \"Females\" geo = \"Canada\" cols_to_keep =", "598752: 'Persons with income of $20,000 and over', 598753: 'Persons with income of", "598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\" df =", "# params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age = \"35 to", "', 598755: 'units ', 598756: 'units ', 598757: 'units ', 598758: 'units ',", "Age, sex, geo, [\"Total income\"], ['Median income (excluding zeros)'], cols_to_keep) assert expected_value ==", "44 years', 598751: '35 to 44 years', 598752: '35 to 44 years', 598753:", "598756: 'units ', 598757: 'units ', 598758: 'units ', 598759: 'units ', 598760:", "', 598759: 'units ', 598760: 'units '}, 'Sex': {598748: 'Females', 598749: 'Females', 598750:", "'}, 'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females', 598753:", "pd.read_csv(path, low_memory=False) # parameters year = 2017 Age = '25 to 34 years'", "2017, 598754: 2017, 598755: 2017, 598756: 2017, 598757: 2017, 598758: 2017, 598759: 2017,", "to 44 years', 598750: '35 to 44 years', 598751: '35 to 44 years',", "years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753:", "'Persons with income of $25,000 and over', 598754: 'Persons with income of $35,000", "and over', 598751: 'Persons with income of $15,000 and over', 598752: 'Persons with", "pd.read_csv(path, low_memory=False) age = \"35 to 44 years\" year = 2017 geo =", "'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with income': {598748: 'Persons with", "df = subset_year_age_sex_geo(df, year, age, sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result ==", "598757: 'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0,", "$75,000 and over', 598757: 'Persons with income of $100,000 and over', 598758: 'Persons", "598750: '35 to 44 years', 598751: '35 to 44 years', 598752: '35 to", "44 years', 598753: '35 to 44 years', 598754: '35 to 44 years', 598755:", "', 598754: 'units ', 598755: 'units ', 598756: 'units ', 598757: 'units ',", "{'Age group': {1550629: '25 to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629:", "df = pd.read_csv(path, low_memory=False) age = \"35 to 44 years\" year = 2017", "parameters year = 2017 Age = '25 to 34 years' sex = \"Females\"", "'Persons with income of $5,000 and over', 598750: 'Persons with income of $10,000", "34 years' sex = \"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex',", "with income': {598748: 'Persons with income under $5,000', 598749: 'Persons with income of", "income of $15,000 and over', 598752: 'Persons with income of $20,000 and over',", "'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year,", "598755: 2017, 598756: 2017, 598757: 2017, 598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR':", "to 44 years', 598758: '35 to 44 years', 598759: '35 to 44 years',", "'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE':", "of $20,000 and over', 598753: 'Persons with income of $25,000 and over', 598754:", "to 34 years' sex = \"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO',", "= {'Age group': {1550629: '25 to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source':", "2017, 598755: 2017, 598756: 2017, 598757: 2017, 598758: 2017, 598759: 2017, 598760: 2017},", "'Persons with income of $50,000 and over', 598756: 'Persons with income of $75,000", "{1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load", "'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females',", "598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0,", "598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755:", "'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load the data path =", "598758: '35 to 44 years', 598759: '35 to 44 years', 598760: '35 to", "{1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding", "and over', 598755: 'Persons with income of $50,000 and over', 598756: 'Persons with", "= r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age = \"35 to 44 years\" year", "'GEO', 'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot(", "to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629:", "group': {1550629: '25 to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total", "'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females',", "of $100,000 and over', 598758: 'Persons with income of $150,000 and over', 598759:", "of $5,000 and over', 598750: 'Persons with income of $10,000 and over', 598751:", "2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ', 598750: 'units ', 598751: 'units", "10390.0}} # params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age = \"35", "load the data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters year", "598754: 'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females', 598760:", "years', 598755: '35 to 44 years', 598756: '35 to 44 years', 598757: '35", "def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25 to 34 years'}, 'GEO': {1550629:", ") def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35 to 44 years', 598749:", "', 598749: 'units ', 598750: 'units ', 598751: 'units ', 598752: 'units ',", "over', 598751: 'Persons with income of $15,000 and over', 598752: 'Persons with income", "598750: 'units ', 598751: 'units ', 598752: 'units ', 598753: 'units ', 598754:", "$35,000 and over', 598755: 'Persons with income of $50,000 and over', 598756: 'Persons", "598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with income':", "income of $50,000 and over', 598756: 'Persons with income of $75,000 and over',", "2017, 598751: 2017, 598752: 2017, 598753: 2017, 598754: 2017, 598755: 2017, 598756: 2017,", "'35 to 44 years', 598758: '35 to 44 years', 598759: '35 to 44", "'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df,", "2017, 598757: 2017, 598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ',", "income of $100,000 and over', 598758: 'Persons with income of $150,000 and over',", "subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25", "zeros)'}, 'VALUE': {1550629: 34800.0}} # load the data path = r\"../../data/raw/11100239.csv\" df =", "np import pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins():", "= \"35 to 44 years\" year = 2017 geo = \"Canada\" sex =", "subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total income\"], ['Median income (excluding zeros)'], cols_to_keep)", "598757: '35 to 44 years', 598758: '35 to 44 years', 598759: '35 to", "{'Age group': {598748: '35 to 44 years', 598749: '35 to 44 years', 598750:", "to 44 years', 598759: '35 to 44 years', 598760: '35 to 44 years'},", "'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada',", "598753: '35 to 44 years', 598754: '35 to 44 years', 598755: '35 to", "income of $200,000 and over', 598760: 'Persons with income of $250,000 and over'},", "'35 to 44 years', 598750: '35 to 44 years', 598751: '35 to 44", "44 years', 598749: '35 to 44 years', 598750: '35 to 44 years', 598751:", "598753: 'units ', 598754: 'units ', 598755: 'units ', 598756: 'units ', 598757:", "'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females',", "'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749:", "598752: 'units ', 598753: 'units ', 598754: 'units ', 598755: 'units ', 598756:", "'35 to 44 years', 598754: '35 to 44 years', 598755: '35 to 44", "', 598753: 'units ', 598754: 'units ', 598755: 'units ', 598756: 'units ',", "', 598758: 'units ', 598759: 'units ', 598760: 'units '}, 'Sex': {598748: 'Females',", "598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757:", "2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ', 598750:", "income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load the data path = r\"../../data/raw/11100239.csv\"", "path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters year = 2017 Age", "'35 to 44 years', 598755: '35 to 44 years', 598756: '35 to 44", "598749: '35 to 44 years', 598750: '35 to 44 years', 598751: '35 to", "# parameters year = 2017 Age = '25 to 34 years' sex =", "years', 598753: '35 to 44 years', 598754: '35 to 44 years', 598755: '35", "598760: '35 to 44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751:", "'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada',", "of $10,000 and over', 598751: 'Persons with income of $15,000 and over', 598752:", "= ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df", "'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada',", "years', 598759: '35 to 44 years', 598760: '35 to 44 years'}, 'GEO': {598748:", "and over', 598752: 'Persons with income of $20,000 and over', 598753: 'Persons with", "'35 to 44 years', 598757: '35 to 44 years', 598758: '35 to 44", "598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758:", "598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with income': {598748: 'Persons with income", "'units ', 598754: 'units ', 598755: 'units ', 598756: 'units ', 598757: 'units", "598753: 'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females', 598759:", "with income of $75,000 and over', 598757: 'Persons with income of $100,000 and", "598751: '35 to 44 years', 598752: '35 to 44 years', 598753: '35 to", "'units ', 598760: 'units '}, 'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females', 598751:", "over', 598753: 'Persons with income of $25,000 and over', 598754: 'Persons with income", "\"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE',", "'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females',", "'Persons with income of $250,000 and over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750:", "1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0,", "'Persons with income': {598748: 'Persons with income under $5,000', 598749: 'Persons with income", "'Persons with income of $200,000 and over', 598760: 'Persons with income of $250,000", "598751: 2017, 598752: 2017, 598753: 2017, 598754: 2017, 598755: 2017, 598756: 2017, 598757:", "year = 2017 geo = \"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df, year,", "and over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017, 598751: 2017, 598752: 2017,", "'35 to 44 years', 598759: '35 to 44 years', 598760: '35 to 44", "source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'},", "with income under $5,000', 598749: 'Persons with income of $5,000 and over', 598750:", "sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value =", "subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35 to", "with income of $5,000 and over', 598750: 'Persons with income of $10,000 and", "598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759:", "598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759:", "2017 geo = \"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df, year, age, sex,", "sex = \"Females\" df = subset_year_age_sex_geo(df, year, age, sex, geo) df = subset_plot_data_for_income_bins(df)", "] df = subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total income\"], ['Median income", "\"Females\" df = subset_year_age_sex_geo(df, year, age, sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result", "44 years', 598750: '35 to 44 years', 598751: '35 to 44 years', 598752:", "44 years', 598755: '35 to 44 years', 598756: '35 to 44 years', 598757:", "of $25,000 and over', 598754: 'Persons with income of $35,000 and over', 598755:", "44 years', 598757: '35 to 44 years', 598758: '35 to 44 years', 598759:", "2017 Age = '25 to 34 years' sex = \"Females\" geo = \"Canada\"", "and over', 598753: 'Persons with income of $25,000 and over', 598754: 'Persons with", "598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760:", "to 44 years', 598760: '35 to 44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada',", "2017, 598752: 2017, 598753: 2017, 598754: 2017, 598755: 2017, 598756: 2017, 598757: 2017,", "$5,000', 598749: 'Persons with income of $5,000 and over', 598750: 'Persons with income", "{1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics':", "= subset_year_age_sex_geo(df, year, age, sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict()", "'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629:", "598758: 'Persons with income of $150,000 and over', 598759: 'Persons with income of", "598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760:", "r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters year = 2017 Age = '25", "'SCALAR_FACTOR': {598748: 'units ', 598749: 'units ', 598750: 'units ', 598751: 'units ',", "group': {598748: '35 to 44 years', 598749: '35 to 44 years', 598750: '35", "income of $25,000 and over', 598754: 'Persons with income of $35,000 and over',", "$10,000 and over', 598751: 'Persons with income of $15,000 and over', 598752: 'Persons", "2017, 598753: 2017, 598754: 2017, 598755: 2017, 598756: 2017, 598757: 2017, 598758: 2017,", "over', 598755: 'Persons with income of $50,000 and over', 598756: 'Persons with income", "'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753:", "598751: 'units ', 598752: 'units ', 598753: 'units ', 598754: 'units ', 598755:", "and over', 598758: 'Persons with income of $150,000 and over', 598759: 'Persons with", "'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with income': {598748:", "'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with income': {598748: 'Persons with income under", "598752: 'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females', 598758:", "{598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754:", "598753: 'Persons with income of $25,000 and over', 598754: 'Persons with income of", "to 44 years', 598751: '35 to 44 years', 598752: '35 to 44 years',", "income under $5,000', 598749: 'Persons with income of $5,000 and over', 598750: 'Persons", "years\" year = 2017 geo = \"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df,", "df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group':", "$200,000 and over', 598760: 'Persons with income of $250,000 and over'}, 'REF_DATE': {598748:", "598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with income': {598748: 'Persons", "'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total income\"],", "598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age =", "{598748: 2017, 598749: 2017, 598750: 2017, 598751: 2017, 598752: 2017, 598753: 2017, 598754:", "44 years', 598759: '35 to 44 years', 598760: '35 to 44 years'}, 'GEO':", "= {'Age group': {598748: '35 to 44 years', 598749: '35 to 44 years',", "income': {598748: 'Persons with income under $5,000', 598749: 'Persons with income of $5,000", "{1550629: 34800.0}} # load the data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False)", "'Females', 598755: 'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'},", "= subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total income\"], ['Median income (excluding zeros)'],", "'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'},", "'25 to 34 years' sex = \"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE',", "598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} #", "import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748:", "'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons with", "import pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result", "598760: 'Persons with income of $250,000 and over'}, 'REF_DATE': {598748: 2017, 598749: 2017,", "598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756:", "598756: 'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0,", "'Females', 598756: 'Females', 598757: 'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748:", "income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median", "20580.0, 598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age", "598754: '35 to 44 years', 598755: '35 to 44 years', 598756: '35 to", "598757: 'units ', 598758: 'units ', 598759: 'units ', 598760: 'units '}, 'Sex':", "'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada',", "'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0,", "of $50,000 and over', 598756: 'Persons with income of $75,000 and over', 598757:", "'units ', 598755: 'units ', 598756: 'units ', 598757: 'units ', 598758: 'units", "'35 to 44 years', 598751: '35 to 44 years', 598752: '35 to 44", "pandas as pd import numpy as np import pytest from ..wrangling import (", "as pd import numpy as np import pytest from ..wrangling import ( subset_plot_data_for_income_bins,", "pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result =", "over', 598750: 'Persons with income of $10,000 and over', 598751: 'Persons with income", "['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df =", "..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age group':", "expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25 to 34", "with income of $250,000 and over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017,", "598755: 'Persons with income of $50,000 and over', 598756: 'Persons with income of", "{1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load the data path", "598754: 'units ', 598755: 'units ', 598756: 'units ', 598757: 'units ', 598758:", "years' sex = \"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age", "'units ', 598756: 'units ', 598757: 'units ', 598758: 'units ', 598759: 'units", "import numpy as np import pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot, subset_year_age_sex_geo", "pd import numpy as np import pytest from ..wrangling import ( subset_plot_data_for_income_bins, subset_plot_data_for_scatter_plot,", "of $75,000 and over', 598757: 'Persons with income of $100,000 and over', 598758:", "to 44 years', 598752: '35 to 44 years', 598753: '35 to 44 years',", "geo) df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age", "'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females',", "598750: 'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females', 598756:", "r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age = \"35 to 44 years\" year =", "'units ', 598757: 'units ', 598758: 'units ', 598759: 'units ', 598760: 'units", "assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25 to", "598759: 'Persons with income of $200,000 and over', 598760: 'Persons with income of", "{1550629: 'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'},", "598759: 'units ', 598760: 'units '}, 'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females',", "598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758:", "'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}}", "598760: 'Canada'}, 'Persons with income': {598748: 'Persons with income under $5,000', 598749: 'Persons", "2017, 598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749: 'units", "1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}}", "598750: 'Persons with income of $10,000 and over', 598751: 'Persons with income of", "with income of $15,000 and over', 598752: 'Persons with income of $20,000 and", "to 44 years\" year = 2017 geo = \"Canada\" sex = \"Females\" df", "48780.0, 598759: 20580.0, 598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path,", "598753: 2017, 598754: 2017, 598755: 2017, 598756: 2017, 598757: 2017, 598758: 2017, 598759:", "'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751:", "44 years', 598754: '35 to 44 years', 598755: '35 to 44 years', 598756:", "'units ', 598758: 'units ', 598759: 'units ', 598760: 'units '}, 'Sex': {598748:", "598755: '35 to 44 years', 598756: '35 to 44 years', 598757: '35 to", "years', 598756: '35 to 44 years', 598757: '35 to 44 years', 598758: '35", "df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629: '25 to 34 years'}, 'GEO':", "'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629: 34800.0}} #", "(excluding zeros)'}, 'VALUE': {1550629: 34800.0}} # load the data path = r\"../../data/raw/11100239.csv\" df", "', 598756: 'units ', 598757: 'units ', 598758: 'units ', 598759: 'units ',", "$150,000 and over', 598759: 'Persons with income of $200,000 and over', 598760: 'Persons", "'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females', 598755: 'Females', 598756: 'Females',", "geo = \"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df, year, age, sex, geo)", "income of $5,000 and over', 598750: 'Persons with income of $10,000 and over',", "income of $20,000 and over', 598753: 'Persons with income of $25,000 and over',", "', 598752: 'units ', 598753: 'units ', 598754: 'units ', 598755: 'units ',", "'Females', 598758: 'Females', 598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750:", "'35 to 44 years', 598749: '35 to 44 years', 598750: '35 to 44", "{1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629: 'Median income (excluding zeros)'}, 'VALUE': {1550629:", "598756: 'Persons with income of $75,000 and over', 598757: 'Persons with income of", "'25 to 34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE':", "'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada',", "path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False) age = \"35 to 44 years\"", "'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629:", "= \"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df, year, age, sex, geo) df", "2017, 598749: 2017, 598750: 2017, 598751: 2017, 598752: 2017, 598753: 2017, 598754: 2017,", "598756: '35 to 44 years', 598757: '35 to 44 years', 598758: '35 to", "598756: 470300.0, 598757: 193910.0, 598758: 48780.0, 598759: 20580.0, 598760: 10390.0}} # params path", "598751: 'Persons with income of $15,000 and over', 598752: 'Persons with income of", "598759: 'Canada', 598760: 'Canada'}, 'Persons with income': {598748: 'Persons with income under $5,000',", "{598748: 'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females', 598754:", "'Canada'}, 'Persons with income': {598748: 'Persons with income under $5,000', 598749: 'Persons with", "# load the data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters", "34800.0}} # load the data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) #", "sex, geo, [\"Total income\"], ['Median income (excluding zeros)'], cols_to_keep) assert expected_value == df.to_dict()", "116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0,", "source', 'Statistics', 'SCALAR_FACTOR', 'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year, Age, sex, geo,", "subset_year_age_sex_geo(df, year, age, sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def", "'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada',", "598757: 2017, 598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units ', 598749:", "and over', 598757: 'Persons with income of $100,000 and over', 598758: 'Persons with", "years', 598750: '35 to 44 years', 598751: '35 to 44 years', 598752: '35", "subset_year_age_sex_geo ) def test_subset_plot_data_for_income_bins(): expected_result = {'Age group': {598748: '35 to 44 years',", "to 44 years', 598754: '35 to 44 years', 598755: '35 to 44 years',", "with income of $20,000 and over', 598753: 'Persons with income of $25,000 and", "598749: 'units ', 598750: 'units ', 598751: 'units ', 598752: 'units ', 598753:", "over', 598758: 'Persons with income of $150,000 and over', 598759: 'Persons with income", "and over', 598760: 'Persons with income of $250,000 and over'}, 'REF_DATE': {598748: 2017,", "'VALUE', ] df = subset_plot_data_for_scatter_plot( df, year, Age, sex, geo, [\"Total income\"], ['Median", "'35 to 44 years', 598753: '35 to 44 years', 598754: '35 to 44", "with income of $35,000 and over', 598755: 'Persons with income of $50,000 and", "'units ', 598752: 'units ', 598753: 'units ', 598754: 'units ', 598755: 'units", "598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756: 'Canada', 598757:", "low_memory=False) # parameters year = 2017 Age = '25 to 34 years' sex", "and over', 598756: 'Persons with income of $75,000 and over', 598757: 'Persons with", "= subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value = {'Age group': {1550629:", "'Total income'}, 'REF_DATE': {1550629: 2017}, 'SCALAR_FACTOR': {1550629: 'units'}, 'Sex': {1550629: 'Females'}, 'Statistics': {1550629:", "598752: '35 to 44 years', 598753: '35 to 44 years', 598754: '35 to", "years', 598754: '35 to 44 years', 598755: '35 to 44 years', 598756: '35", "598749: 'Persons with income of $5,000 and over', 598750: 'Persons with income of", "598758: 'units ', 598759: 'units ', 598760: 'units '}, 'Sex': {598748: 'Females', 598749:", "'Canada', 598760: 'Canada'}, 'Persons with income': {598748: 'Persons with income under $5,000', 598749:", "2017, 598750: 2017, 598751: 2017, 598752: 2017, 598753: 2017, 598754: 2017, 598755: 2017,", "year, Age, sex, geo, [\"Total income\"], ['Median income (excluding zeros)'], cols_to_keep) assert expected_value", "with income of $50,000 and over', 598756: 'Persons with income of $75,000 and", "data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters year = 2017", "{598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754:", "598755: 'Canada', 598756: 'Canada', 598757: 'Canada', 598758: 'Canada', 598759: 'Canada', 598760: 'Canada'}, 'Persons", "'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females', 598752: 'Females', 598753: 'Females', 598754: 'Females',", "44 years', 598752: '35 to 44 years', 598753: '35 to 44 years', 598754:", "{598748: 'units ', 598749: 'units ', 598750: 'units ', 598751: 'units ', 598752:", "age, sex, geo) df = subset_plot_data_for_income_bins(df) assert expected_result == df.to_dict() def test_subset_plot_data_for_scatter_plot(): expected_value", "the data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters year =", "'Persons with income of $75,000 and over', 598757: 'Persons with income of $100,000", "expected_result = {'Age group': {598748: '35 to 44 years', 598749: '35 to 44", "598759: 'Females', 598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0,", "'units ', 598753: 'units ', 598754: 'units ', 598755: 'units ', 598756: 'units", "598755: 'units ', 598756: 'units ', 598757: 'units ', 598758: 'units ', 598759:", "= 2017 geo = \"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df, year, age,", "years', 598760: '35 to 44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada',", "$15,000 and over', 598752: 'Persons with income of $20,000 and over', 598753: 'Persons", "years', 598757: '35 to 44 years', 598758: '35 to 44 years', 598759: '35", "to 44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752:", "'units ', 598749: 'units ', 598750: 'units ', 598751: 'units ', 598752: 'units", "598750: 2017, 598751: 2017, 598752: 2017, 598753: 2017, 598754: 2017, 598755: 2017, 598756:", "income of $10,000 and over', 598751: 'Persons with income of $15,000 and over',", "'units ', 598751: 'units ', 598752: 'units ', 598753: 'units ', 598754: 'units", "598756: 2017, 598757: 2017, 598758: 2017, 598759: 2017, 598760: 2017}, 'SCALAR_FACTOR': {598748: 'units", "income of $35,000 and over', 598755: 'Persons with income of $50,000 and over',", "44 years'}, 'GEO': {598748: 'Canada', 598749: 'Canada', 598750: 'Canada', 598751: 'Canada', 598752: 'Canada',", "598750: 'Canada', 598751: 'Canada', 598752: 'Canada', 598753: 'Canada', 598754: 'Canada', 598755: 'Canada', 598756:", "over', 598752: 'Persons with income of $20,000 and over', 598753: 'Persons with income", "= r\"../../data/raw/11100239.csv\" df = pd.read_csv(path, low_memory=False) # parameters year = 2017 Age =", "598760: 'units '}, 'Sex': {598748: 'Females', 598749: 'Females', 598750: 'Females', 598751: 'Females', 598752:", "with income of $200,000 and over', 598760: 'Persons with income of $250,000 and", "1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0, 598757: 193910.0, 598758: 48780.0,", "with income of $10,000 and over', 598751: 'Persons with income of $15,000 and", "to 44 years', 598753: '35 to 44 years', 598754: '35 to 44 years',", "years', 598752: '35 to 44 years', 598753: '35 to 44 years', 598754: '35", "598754: 'Persons with income of $35,000 and over', 598755: 'Persons with income of", "= \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source', 'Statistics', 'SCALAR_FACTOR',", "\"Canada\" sex = \"Females\" df = subset_year_age_sex_geo(df, year, age, sex, geo) df =", "598759: 20580.0, 598760: 10390.0}} # params path = r\"../../data/raw/11100008.csv\" df = pd.read_csv(path, low_memory=False)", "geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income source', 'Statistics',", "year = 2017 Age = '25 to 34 years' sex = \"Females\" geo", "', 598751: 'units ', 598752: 'units ', 598753: 'units ', 598754: 'units ',", "'units ', 598759: 'units ', 598760: 'units '}, 'Sex': {598748: 'Females', 598749: 'Females',", "34 years'}, 'GEO': {1550629: 'Canada'}, 'Income source': {1550629: 'Total income'}, 'REF_DATE': {1550629: 2017},", "= \"Females\" geo = \"Canada\" cols_to_keep = ['REF_DATE', 'GEO', 'Sex', 'Age group', 'Income", "to 44 years', 598749: '35 to 44 years', 598750: '35 to 44 years',", "of $250,000 and over'}, 'REF_DATE': {598748: 2017, 598749: 2017, 598750: 2017, 598751: 2017,", "income of $75,000 and over', 598757: 'Persons with income of $100,000 and over',", "598760: 'Females'}, 'VALUE': {598748: 116190.0, 598749: 2214880.0, 598750: 2098920.0, 598751: 1966980.0, 598752: 1836860.0,", "over', 598756: 'Persons with income of $75,000 and over', 598757: 'Persons with income", "import pandas as pd import numpy as np import pytest from ..wrangling import", "'Persons with income of $15,000 and over', 598752: 'Persons with income of $20,000", "2098920.0, 598751: 1966980.0, 598752: 1836860.0, 598753: 1699380.0, 598754: 1406370.0, 598755: 958310.0, 598756: 470300.0,", "years', 598751: '35 to 44 years', 598752: '35 to 44 years', 598753: '35", "'VALUE': {1550629: 34800.0}} # load the data path = r\"../../data/raw/11100239.csv\" df = pd.read_csv(path,", "'Persons with income of $10,000 and over', 598751: 'Persons with income of $15,000", "over', 598759: 'Persons with income of $200,000 and over', 598760: 'Persons with income", "{598748: '35 to 44 years', 598749: '35 to 44 years', 598750: '35 to" ]
[ "\"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\":", "= [ { \"label\": \"GENERIC_CASE_CITATION\", \"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"},", "\"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}},", "True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\":", "\"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\": \"?\"},", "\"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\",", "True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\":", "\"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\":", "[ { \"label\": \"GENERIC_CASE_CITATION\", \"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\":", "\"GENERIC_CASE_CITATION\", \"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"},", "{\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"},", "CITATION_PATTERNS = [ { \"label\": \"GENERIC_CASE_CITATION\", \"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\":", "{\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\":", "[ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True,", "{\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"},", "\"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"LIKE_NUM\": True}, ], }", "{\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"LIKE_NUM\": True},", "\"label\": \"GENERIC_CASE_CITATION\", \"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\":", "{\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"},", "{\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\":", "{ \"label\": \"GENERIC_CASE_CITATION\", \"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True,", "\"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\":", "\".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"LIKE_NUM\": True}, ],", "True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"},", "\"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\":", "\"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\":", "\"?\"}, {\"LIKE_NUM\": True, \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\":", "\"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"LIKE_NUM\": True}, ], } ]", "{\"REGEX\": \"^[A-Z]\"}, \"OP\": \"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\",", "\"?\"}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"TEXT\": {\"REGEX\": r\"^[A-Z\\.]\"}}, {\"ORTH\": \".\", \"OP\": \"?\"}, {\"LIKE_NUM\":", "\"pattern\": [ {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"SHAPE\": \"dddd\"}, {\"IS_BRACKET\": True, \"OP\": \"?\"}, {\"LIKE_NUM\":" ]
[ "= lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None: privatedir_line =", "ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type = \"ldb\" sid_generator = \"internal\" if", "logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" %", "group policy GUIDs # Default GUID for default policy are described at #", "\"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\"", "low: The lowest USN modified by this upgrade :param high: The highest USN", "dir\") # This is stored without path prefix for the \"privateKeytab\" attribute in", "else: wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid =", ":param guid: The GUID of the policy :return: A string with the complete", "setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn})", "the dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid", "\"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\"", "does not make much sense values larger than 1000000000 # as the upper", "= True # Set the SYSVOL_ACL on the sysvol folder and subfolder (first", "= value def __str__(self): return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified", "The DNS name of the domain :param domaindn: The DN of the domain", "file. :param realm: Realm name :param dnsdomain: DNS Domain name :param private_dir: Path", "serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None,", "\"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns", "paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind gid", "sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin", "since last provision. :param samdb: An LDB object connect to sam.ldb :param low:", "start it up try: os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp,", "tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE]", "No LDAP backend\" if provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" %", "DN of the domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except OSError:", "SAM Database. :note: This will wipe the main SAM database file! \"\"\" #", "self.hklm = None self.hkcu = None self.hkcr = None self.hku = None self.hkpd", "names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain,", "Database! :note: This function always removes the local SAM LDB file. The erase", "lockdir_line }) # reload the smb.conf lp.load(smbconf) # and dump it without any", "\"member server\": smbconfsuffix = \"member\" elif serverrole == \"standalone\": smbconfsuffix = \"standalone\" if", "change these default values without discussion with the # team and/or release manager.", "range.append(tab[0]) range.append(tab[1]) idx = idx + 1 return range else: return None class", "variables. \"\"\" assert ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except", "domaindn, samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and the policy folders", "to subsitute in LDIF. :param nocontrols: Optional list of controls, can be None", "hostname.upper() # remove forbidden chars newnbname = \"\" for x in netbiosname: if", "Local IPv4 IP :param hostip6: Local IPv6 IP :param hostname: Local hostname :param", "the created secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp)", "from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry", "Please remove the %s file and let provision generate it\" % (lp.get(\"workgroup\").upper(), domain,", "role '%s'! Please remove the smb.conf file and let provision generate it\" %", "url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD schema\")", "Loadparm context \"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE)", "\"gc._msdcs IN AAAA \" + hostip6 else: hostip6_base_line = \"\" hostip6_host_line = \"\"", "The SID of the domain :param domaindn: The DN of the domain (ie.", "name), SYSVOL_ACL, str(domainsid)) for name in dirs: if canchown: os.chown(os.path.join(root, name), -1, gid)", "and not lp.get(\"posix:eadb\"): if targetdir is not None: privdir = os.path.join(targetdir, \"private\") else:", "SID, realm or netbios domain at a time, # but we don't delete", "want to wipe and re-initialise the database, not start it up try: os.unlink(samdb_path)", "# # Based on the original in EJS: # Copyright (C) <NAME> <<EMAIL>>", "the SAM db :param lp: an LP object \"\"\" # Set ACL for", "by (upgrade)provision, 0 is this value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" %", "the secrets database. :param session_info: Session info. :param credentials: Credentials :param lp: Loadparm", "if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn,", "os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create", "4 and AD schema\") # Load the schema from the one we computed", "dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp):", "the new named.conf file. :param realm: Realm name :param dnsdomain: DNS Domain name", "sense values larger than 1000000000 # as the upper range of the rIDAvailablePool", "guid): \"\"\"Return the physical path of policy given its guid. :param sysvolpath: Path", "the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if hostip6 is not None:", "configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE)))", "tries to ensure that we don't have more # than one record for", "the \"Domain adminstrators\" group :param domainsid: The SID of the domain :param dnsdomain:", "msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"]", "database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account found\")", "names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials,", "highest USN modified by this upgrade :param replace: A boolean indicating if the", "secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None", "file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\"", "# Copyright (C) <NAME> <<EMAIL>> 2008-2009 # # Based on the original in", "\"\"\"Import a LDIF a file into a LDB handle, optionally substituting variables. :note:", "{ \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), {", "the secrets database. :note: This function does not handle exceptions and transaction on", "None self.hkcr = None self.hku = None self.hkpd = None self.hkpt = None", "}) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit()", "= [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is", "adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a", "worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() !=", "lp.load(smbconf) # and dump it without any values that are the default #", "idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup", "names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb,", "None self.private_dir = None class ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn =", "samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now we can connect to the DB", "names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries", "sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf lp.load(smbconf)", "the private dir. :param ldb: LDB file to import data into :param ldif_path:", "self.rootdn = None self.domaindn = None self.configdn = None self.schemadn = None self.ldapmanagerdn", "and then populate the database. :note: This will wipe the Sam Database! :note:", "figure out if the field have been modified since last provision. :param samdb:", "ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None):", "dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False,", "GNU General Public License as published by # the Free Software Foundation; either", "+ hostip hostip_host_line = hostname + \" IN A \" + hostip gc_msdcs_ip_line", "if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif", "domaindn, lp): \"\"\"Set the ACL for the sysvol share and the subfolders :param", "the database, but don's load the global schema and don't connect # quite", "delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the field", "policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p", "krbtgtpass = samba.generate_random_password(128, 255) if machinepass is None: machinepass = samba.generate_random_password(128, 255) if", "else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp is", "is not None: # now display slapd_command_file.txt to show how slapd must be", "don't delete the old record that we are about to modify, # because", "if serverrole == \"domain controller\": if domain is None: # This will, for", "255) if dnspass is None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass is None:", "be equal to hostname '%s'!\" % (realm, hostname)) if netbiosname.upper() == realm: raise", "[str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"] = [\"top\",", "}) # This is partially Samba4 specific and should be replaced by the", "dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" %", "if policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is", "# it under the terms of the GNU General Public License as published", "import b64encode import os import re import pwd import grp import logging import", "\"etc\", \"smb.conf\") elif smbconf is None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf))", "samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn)", "is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"),", "= None self.hku = None self.hkpd = None self.hkpt = None self.samdb =", "elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: #", "policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid, domainguid,", "names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename,", "samdb.transaction_start() try: # Set the domain functionality levels onto the database. # Various", "admin configuration file. :param path: Path to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"),", "in sam.ldb This field is used to track range of USN modified by", "physical path of policy given its guid. :param sysvolpath: Path to the sysvol", "folders beneath. :param sysvol: Physical path for the sysvol folder :param dnsdomain: The", "slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this wipes all", "biggest USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return", "into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are installed, your Samba4 server will", "this upgrade :param high: The highest USN modified by this upgrade :param replace:", ":param domainsid: The SID of the domain :param domaindn: The DN of the", "FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp,", "FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL", "policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its own domain.\"\"\" assert isinstance(invocationid,", "equal to netbios hostname '%s'!\" % (realm, netbiosname)) if domain == realm: raise", "check. :return: Value return by first names list. \"\"\" for name in names:", "def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess", "# on the provision/join command line are set in the resulting smb.conf f", "os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL", "future, this might be determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg", "is %u-%u. The default is %u.\" % ( 1000, 1000000000, 1000) raise ProvisioningError(error)", "domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain", "lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param path: Path", "create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a file containing zone statements suitable for", "lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None: privatedir_line = \"private dir =", "A \" + hostip else: hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line =", "% guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if", "\"\"\" tab = [] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\",", "None: configdn = \"CN=Configuration,\" + rootdn if schemadn is None: schemadn = \"CN=Schema,\"", "smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\":", "AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" + hostip6 else:", "this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn", "lp) logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm,", "%s to bind gid %u\" % ( dns_dir, paths.bind_gid)) if targetdir is None:", "upper range of the rIDAvailablePool is 1073741823 and # we don't want to", "at the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn,", "is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb,", "= os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775) # we need", "\"\"\"Join a host to its own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is", "if dnsdomain is None: dnsdomain = realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower())", "substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn})", "= samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No external IPv4 address has been", "str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid,", "Role: %s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain)", "serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid", "domaindn: The DN of the domain (ie. DC=...) :param samdb: An LDB object", "\"\"\"Modify a ldb in the private dir. :param ldb: LDB object. :param ldif_path:", "the default GPO for a domain :param sysvolpath: Physical path for the sysvol", "present in the provision :param samdb: A LDB object pointing to the sam.ldb", "context. :param dnsdomain: DNS Domain name \"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private", "except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No", "what level of AD we are emulating. # These will be fixed into", "setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid,", "controls, can be None for no controls \"\"\" assert isinstance(ldif_path, str) data =", "or \"users\", 'users', 'other', 'staff']) if wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"])", "\"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line })", "template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if paths.sysvol", "the privileges database. :param path: Path to the privileges database. :param session_info: Session", "os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\")", "'%s' must not be equal to netbios hostname '%s'!\" % (realm, netbiosname)) if", "a domain :param sysvolpath: Physical path for the sysvol folder :param dnsdomain: DNS", "Function to try (should raise KeyError if not found) :param names: Names to", "ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid", "is None: backend_type = \"ldb\" sid_generator = \"internal\" if backend_type == \"fedora-ds\": sid_generator", "domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits", "equal to hostname '%s'!\" % (realm, hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names:", "= SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and", "LDB object pointing to the sam.ldb :param basedn: A string containing the base", "use.\"\"\" if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if", "the UNIX nobody user. :param users_gid: gid of the UNIX users group. :param", "mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid):", "sysvol/<dnsname>/Policies folder and the policy folders beneath. :param sysvol: Physical path for the", "run SAMBA 4 on a domain and forest function level which itself is", "\"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" %", "shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775) # we need to freeze the", "want to run SAMBA 4 with a next_rid of %u, \" % (next_rid)", "earlier samdb.set_schema(schema) # Set the NTDS settings DN manually - in order to", "InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain = lp.get(\"realm\") if dnsdomain is None or", "replaced by the correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain,", "logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" %", "the keytab and previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain,", "database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain +", "in LDIF. :param nocontrols: Optional list of controls, can be None for no", "os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s", "= realm names.netbiosname = netbiosname names.hostname = hostname names.sitename = sitename names.serverdn =", "== \"domain controller\": if domain is None: # This will, for better or", "= \"CN=Schema,\" + configdn if sitename is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn", "logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), # seconds", "self.samdb = None self.idmapdb = None self.secrets = None self.keytab = None self.dns_keytab", "the sam.ldb :return: an integer corresponding to the highest USN modified by (upgrade)provision,", "credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials,", "domain :param dnsdomain: The DNS name of the domain :param domaindn: The DN", "\"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name):", "samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL", "inclusion in a named.conf file (including GSS-TSIG configuration). :param path: Path of the", "of the GNU General Public License as published by # the Free Software", "is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def", "provision. :param samdb: An LDB object connect to sam.ldb :param low: The lowest", "names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path of policy", "= [] tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\")", "logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\")", "server\": smbconfsuffix = \"member\" elif serverrole == \"standalone\": smbconfsuffix = \"standalone\" if sid_generator", "\"\" lockdir_line = \"\" if sid_generator == \"internal\": sid_generator_line = \"\" else: sid_generator_line", "{ \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers", "IN AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" + hostip6", "= realm.upper() if lp is None: lp = samba.param.LoadParm() #Load non-existant file if", "paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if", "hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line,", "of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\":", "domain policy :param policyguid_dc: GUID of the default domain controler policy \"\"\" policy_path", "assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL =", "IDmap db object. :param sid: The domain sid. :param domaindn: The domain DN.", "= None self.hklm = None self.hkcu = None self.hkcr = None self.hku =", "pass os.mkdir(dns_dir, 0775) # we need to freeze the zone while we update", "Settings,%s\" % names.serverdn) # And now we can connect to the DB -", "domaindn names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain", "names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc", "\"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"),", "= domain.upper() assert realm is not None realm = realm.upper() if lp is", "DN manually - in order to have it already around # before the", "secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the", "get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\"", "logger.warning(\"More than one IPv4 address found. Using %s.\", hostip) if serverrole is None:", "folder :param dnsdomain: DNS name of the AD domain :param guid: The GUID", "a dns_update_list file\"\"\" # note that we use no variable substitution on this", "names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid,", "the zone while we update the contents if targetdir is None: rndc =", "by # the Free Software Foundation; either version 3 of the License, or", "\"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a file containing", "/etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are installed, your Samba4 server will be", ":param realm: Realm name :param dnsdomain: DNS Domain name :param private_dir: Path to", "if invocationid is None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not", "credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp,", "secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s' % shortname ] if secure_channel_type", "'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names:", "variables. :note: Either all LDIF data will be added or none (using transactions).", "return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin configuration file. :param", "attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx = 0 p = re.compile(r'-') for", "realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to short domain name", "length to be <16 netbiosname = newnbname[0:15] assert netbiosname is not None netbiosname", "domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid", "done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN update", "\"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\"", "None: logger.info(\"Existing smb.conf does not have a [netlogon] share, but you are configuring", "a LDIF a file into a LDB handle, optionally substituting variables. :note: Either", "handle exceptions and transaction on purpose, it's up to the caller to do", "for del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) ==", "idmap: IDmap db object. :param sid: The domain sid. :param domaindn: The domain", "from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend,", "for better or worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper()", "now we can connect to the DB - the schema won't be loaded", "The domain sid. :param domaindn: The domain DN. :param root_uid: uid of the", "# We use options=[\"modules:\"] to stop the modules loading - we # just", "to chown %s to bind gid %u\" % ( dns_dir, paths.bind_gid)) if targetdir", "re import pwd import grp import logging import time import uuid import socket", "range of USN modified by provision and upgradeprovision. This value is used afterward", "\"\"\"Setup the privileges database. :param path: Path to the privileges database. :param session_info:", "Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill == FILL_FULL:", "try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None if targetdir is", "that we don't have more # than one record for this SID, realm", "parameters that were set # on the provision/join command line are set in", "adminpass) if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend", "domainsid, domaindn, samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and the policy", "\"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\")", "\"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb,", "domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is not None:", "# Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 #", "for the created secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info,", "secrets_ldb.transaction_commit() # the commit creates the dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir,", "provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: # now display slapd_command_file.txt to show how", "first names list. \"\"\" for name in names: try: return nssfn(name) except KeyError:", "is None: serverrole = \"standalone\" assert serverrole in (\"domain controller\", \"member server\", \"standalone\")", "if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #force", ":param ntdsguid: GUID of the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if", "names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS", "(upgrade)provision, 0 is this value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE,", "krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass is None: machinepass =", "upgrade :param high: The highest USN modified by this upgrade :param replace: A", "License for more details. # # You should have received a copy of", "logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn", "realm '%s'! Please remove the smb.conf file and let provision generate it\" %", "%s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is None: serverrole = lp.get(\"server role\")", "\"DOMAINDN\": names.domaindn}) # add the NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\" %", "dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out a DNS zone file,", "= \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type ==", ":param lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp)", "= open(smbconf, 'r').read() data = data.lstrip() if data is None or data ==", "under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn result.paths = paths result.lp", "import pwd import grp import logging import time import uuid import socket import", "the above files are installed, your Samba4 server will be ready to use\")", "for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx +", "\"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not None: if dnsdomain is None:", "DNS name of the AD domain :param guid: The GUID of the policy", "or an upgradeprovision :param sam: An LDB object pointing to the sam.ldb :return:", "UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\",", "An LDB object connect to sam.ldb :param low: The lowest USN modified by", "getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path of policy given its guid. :param", "domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not be equal to short", "gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located at %s into", "= os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain,", "set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN in sam.ldb This field is used", "private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to a secrets database.", "\"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload", "- the schema won't be loaded from the # DB samdb.connect(path) if fill", "was created when the Schema object was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add,", "schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if hostname is None: hostname", ":param ldif_path: Path of the LDIF file to load :param subst_vars: Optional variables", "spn = [ 'HOST/%s' % shortname ] if secure_channel_type == SEC_CHAN_BDC and dnsname", "domaindn: The DN of the domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid)", "is None: sid_generator = \"internal\" assert domain is not None domain = domain.upper()", "= '127.0.0.1' else: hostip = hostips[0] if len(hostips) > 1: logger.warning(\"More than one", "serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res", "for policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"]))", "USN modified by this upgrade :param replace: A boolean indicating if the range", "False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable", ":param ldb: LDB object. :param ldif_path: LDIF file path. :param subst_vars: Optional dictionary", "session_info: Session info. :param credentials: Credentials :param lp: Loadparm context :return: LDB handle", "in %s must match chosen server role '%s'! Please remove the smb.conf file", "= \"standalone\" assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if serverrole ==", "setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass,", "Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\"", "= \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL =", "update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A", "SMB/CIFS implementation. # backend code for provisioning a Samba4 server # Copyright (C)", "samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and the policy folders beneath.", "we update the contents if targetdir is None: rndc = ' '.join(lp.get(\"rndc command\"))", "# seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\":", "secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start()", "optionally substituting variables. :note: Either all LDIF data will be added or none", "if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets", "logger.info(\"Please either remove %s or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\")))", "\"\"\"Write out a dns_update_list file\"\"\" # note that we use no variable substitution", "files are installed, your Samba4 server will be ready to use\") logger.info(\"Server Role:", "= \"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError:", "credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None,", "schema from the one we computed earlier samdb.set_schema(schema) # Set the NTDS settings", "dom_for_fun_level # Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole,", "configdn) return names def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None):", "ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp,", "SAM database. Alternatively, provision() may call this, and then populate the database. :note:", "done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths,", "= get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb, 0,", "setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up", "class ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn = None self.configdn = None", ":param private_dir: Path to private directory :param keytab_name: File name of DNS keytab", "os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to", "domain :param domaindn: The DN of the domain (ie. DC=...) \"\"\" try: os.chown(sysvol,", "This program is free software; you can redistribute it and/or modify # it", "domain and forest function level which itself is higher than its actual DC", "% (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755)", "see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None", "names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting", "self.configdn = None self.schemadn = None self.ldapmanagerdn = None self.dnsdomain = None self.realm", "# # This program is free software; you can redistribute it and/or modify", "# Unix SMB/CIFS implementation. # backend code for provisioning a Samba4 server #", "= domaindn result.paths = paths result.lp = lp result.samdb = samdb return result", "\"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\":", "found) :param names: Names to check. :return: Value return by first names list.", "IPv4 addresses\") hostips = samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No external IPv4", "to private directory :param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"),", "of the \"Domain adminstrators\" group :param domainsid: The SID of the domain :param", "secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]]", "field is used to track range of USN modified by provision and upgradeprovision.", "# note that we use no variable substitution on this file # the", "serverrole == \"member server\": smbconfsuffix = \"member\" elif serverrole == \"standalone\": smbconfsuffix =", "not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775)", "backend_credentials, lp): \"\"\"Setup the secrets database. :note: This function does not handle exceptions", "eadb=False, lp=None): \"\"\"Create a new smb.conf file based on a couple of basic", "None self.keytab = None self.dns_keytab = None self.dns = None self.winsdb = None", "try: return nssfn(name) except KeyError: pass raise KeyError(\"Unable to find user/group in %r\"", "in os.walk(sysvol, topdown=False): for name in files: if canchown: os.chown(os.path.join(root, name), -1, gid)", "\"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\":", "settings to use.\"\"\" if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios", "time import uuid import socket import urllib import shutil import ldb from samba.auth", "Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for", "is None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass is None: # Make a", "slapd_command_file.txt to show how slapd must be # started next time logger.info(\"Use later", "if the range should replace any existing one or appended (default) \"\"\" tab", "job. :param path: Path to the secrets database. :param session_info: Session info. :param", "domain = netbiosname if domaindn is None: domaindn = \"DC=\" + netbiosname if", "% (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if paths.sysvol is None: logger.info(\"Existing", "name '%s'!\" % (realm, domain)) if rootdn is None: rootdn = domaindn if", "if secure_channel_type == SEC_CHAN_BDC and dnsname is not None: # we are a", "= None self.hkpd = None self.hkpt = None self.samdb = None self.idmapdb =", "names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a", "% (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None: domaindn = \"DC=\" + dnsdomain.replace(\".\",", "None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field provisionUSN in sam.ldb This", "Please remove the smb.conf file and let provision generate it\" % (lp.get(\"server role\").upper(),", "entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx + 1 return range", "ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a file into a", "either remove %s or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert", "samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain", "not specified in supplied %s!\" % lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper()", "= samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl = ndr_unpack(security.descriptor,", "%s. Please remove the smb.conf file and let provision generate it\" % lp.configfile)", "not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to", "def __init__(self, value): self.value = value def __str__(self): return \"ProvisioningError: \" + self.value", "(ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except OSError: canchown = False else:", "res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"]", "much sense values larger than 1000000000 # as the upper range of the", "directory :param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, {", "krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain", "\"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise", "ldb: LDB file to import data into :param ldif_path: Path of the LDIF", "default policy are described at # \"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx", "os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"#", "= os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path,", "idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid +", "this wipes all existing data! \"\"\" if domainsid is None: domainsid = security.random_sid()", "setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a file containing", "name\") if netbiosname is None: netbiosname = hostname # remove forbidden chars newnbname", "a big impact on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is", "set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding", "zone statements suitable for inclusion in a named.conf file (including GSS-TSIG configuration). :param", "\"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up", "domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\"))", "names.hostname = hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename,", "= IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the", "\"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' %", "= lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in", "import re import pwd import grp import logging import time import uuid import", "Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # #", "include file for BIND\", paths.namedconf) logger.info(\"and %s for further documentation required for secure", "os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu", "need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid))", "the provision (ie. DC=foo, DC=bar) :return: The biggest USN in the provision\"\"\" res", "domain == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to short", "the commit creates the dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if", "= \"# No LDAP backend\" if provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend:", "itself is higher than its actual DC function level (2008_R2). This won't work!\")", "is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin DN: %s\"", "Provision does not make much sense values larger than 1000000000 # as the", "\"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise", "if ntdsguid is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\"", "upgrade :param replace: A boolean indicating if the range should replace any existing", "path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir", "and let provision generate it\" % lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names:", "%s!\" % lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") == \"\":", "self.shareconf = None self.hklm = None self.hkcu = None self.hkcr = None self.hku", "realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba 4 has been \" \"generated at", "def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings", "logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb,", "names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str(", "else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password())", "\"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path", "ldb: LDB file to import into. :param ldif_path: Path to the LDIF file.", "a ldb in the private dir. :param ldb: LDB file to import data", "backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4", "the keytab code to update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn", "'%s'!\" % (realm, hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must", "ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the", "Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type =", "in particular) need # to know what level of AD we are emulating.", "statements suitable for inclusion in a named.conf file (including GSS-TSIG configuration). :param path:", "setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if paths.sysvol is None: logger.info(\"Existing smb.conf does", "descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)),", "None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid else: domainguid_line = \"\" descr =", "credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS settings DN manually - in", "not None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is", "hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab)", ":param domaindn: The DN of the domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1,", "setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the partitions for", "smbconf is None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install", "acl, domsid) for name in dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol,", "ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return the biggest USN present", "findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup", "policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None,", "ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg)", "self.paths = None self.domaindn = None self.lp = None self.samdb = None def", "def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write", "won't be loaded from the # DB samdb.connect(path) if fill == FILL_DRS: return", "reload the smb.conf lp.load(smbconf) # and dump it without any values that are", "attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return", ":param dnsdomain: The DNS name of the domain :param domaindn: The DN of", "of the AD domain :param guid: The GUID of the policy :return: A", "should replace any existing one or appended (default) \"\"\" tab = [] if", "provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\":", "Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res:", "# \"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\"", "runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain,", "return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was not a", "invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\"))", "in netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname,", "return None class ProvisionResult(object): def __init__(self): self.paths = None self.domaindn = None self.lp", "weird errors # loading an empty smb.conf gives, then we need to be", "it should be # replicated with DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain,", "(paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if", "paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a", "\"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self,", "os.system(rndc + \" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out", "session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up", "paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a", "names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid,", "resulting smb.conf f = open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid,", "whether the current install seems ok. :param lp: Loadparm context :param session_info: Session", "== FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole ==", "SYSVOL_ACL, str(domainsid)) # Set acls on Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain,", "a new smb.conf if there isn't one there already if os.path.exists(smbconf): # if", "\".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir,", "it will be useful, # but WITHOUT ANY WARRANTY; without even the implied", "ProvisioningError(\"guess_names: Realm '%s' must not be equal to short domain name '%s'!\" %", "users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res", "in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn =", "\"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up", "= netbiosname if domaindn is None: domaindn = \"DC=\" + netbiosname if not", "use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\"", "Make a new, random password between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255)", "= socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname is None: netbiosname = hostname", "= [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname]", "res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by a provision or an", "the first DC, it should be # replicated with DNS replication create_zone_file(lp, logger,", "\"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "Database. :note: This will wipe the main SAM database file! \"\"\" # Provision", "domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None,", "paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now commit the", "ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and", "sysvol folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files", "SID of the domain :param dnsdomain: The DNS name of the domain :param", "= rootdn names.domaindn = domaindn names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn =", "serverrole == \"domain controller\": if domain is None: # This will, for better", "if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is", "= \"objectGUID: %s\\n-\" % domainguid else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb,", "Now commit the secrets.ldb to disk secrets_ldb.transaction_commit() # the commit creates the dns.keytab,", "logger.info(\"and %s for further documentation required for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs", "!= ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this attribute does not exist in", "Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper()", "# Various module (the password_hash module in particular) need # to know what", "a complete SAM Database. :note: This will wipe the main SAM database file!", "didn't exist --abartlet data = open(smbconf, 'r').read() data = data.lstrip() if data is", "paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None):", "newnbname[0:15] assert netbiosname is not None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise", "create/adapt the group policy GUIDs # Default GUID for default policy are described", "= LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\": provision_backend =", "(should raise KeyError if not found) :param names: Names to check. :return: Value", "realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s", "ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None,", "get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN,", "schemadn = \"CN=Schema,\" + configdn if sitename is None: sitename=DEFAULTSITE names = ProvisionNames()", "setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\":", "schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp,", "data = data.lstrip() if data is None or data == \"\": make_smbconf(smbconf, hostname,", ":param samdb: SamDB object. :param idmap: IDmap db object. :param sid: The domain", "False) if len(hostips) == 0: logger.warning(\"No external IPv4 address has been found. Using", "serverrole is None: serverrole = lp.get(\"server role\") if serverrole is None: raise ProvisioningError(\"guess_names:", "sam names to unix names. :param samdb: SamDB object. :param idmap: IDmap db", "# These will be fixed into the database via the database # modifictions", "version }) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn,", "policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb,", "names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb,", "\"krb5Keytab\", \"privateKeytab\"] if realm is not None: if dnsdomain is None: dnsdomain =", "are configuring a DC.\") logger.info(\"Please either remove %s or see the template at", "configuration). :param path: Path of the new named.conf file. :param realm: Realm name", "This complex expression tries to ensure that we don't have more # than", "realm, domainguid, ntdsguid): \"\"\"Write out a DNS zone file, from the info in", "sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if hostname is None: hostname = socket.gethostname().split(\".\")[0]", "socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden chars newnbname = \"\" for x", "os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku =", "\"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % (", "% names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration data\")", "setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]),", "maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba 4 has", "\"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir = \"", "slapd must be # started next time logger.info(\"Use later the following commandline to", "is not None realm = realm.upper() if lp is None: lp = samba.param.LoadParm()", "file to import into. :param ldif_path: Path to the LDIF file. :param subst_vars:", "findnss(nssfn, names): \"\"\"Find a user or group from a list of possibilities. :param", "\"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf", "secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if", "ACL for the sysvol share and the subfolders :param samdb: An LDB object", "free software; you can redistribute it and/or modify # it under the terms", "but you\" \" are configuring a DC.\") logger.info(\"Please either remove %s or see", "str) if hostip6 is not None: hostip6_base_line = \" IN AAAA \" +", "\\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\", "os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not", "session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if", "for the sysvol folder :param dnsdomain: The DNS name of the domain :param", "if len(hostips) == 0: logger.warning(\"No external IPv4 address has been found. Using loopback.\")", "\"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range =", "samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\")", "= hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn)", "sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL for the sysvol share", "but you are configuring a DC.\") logger.info(\"Please either remove %s or see the", "subst_vars): \"\"\"Import a LDIF a file into a LDB handle, optionally substituting variables.", "dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the right msDS-SupportedEncryptionTypes into", "logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege,", "serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(),", ":param domaindn: DN of the Domain :param hostip: Local IPv4 IP :param hostip6:", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "\"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499), }) # This", "lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb,", "samdb.connect(path) if fill == FILL_DRS: return samdb samdb.transaction_start() try: # Set the domain", "that would delete the keytab and previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs,", "not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None: smbconf =", "setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, })", "lp.get(\"posix:eadb\"): if targetdir is not None: privdir = os.path.join(targetdir, \"private\") else: privdir =", "self.domain = None self.hostname = None self.sitename = None self.smbconf = None def", "lp, domsid): setntacl(lp, path, acl, domsid) for root, dirs, files in os.walk(path, topdown=False):", "= \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam", "# # This program is distributed in the hope that it will be", "\"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we", "paths :param realm: Realm name :param dnsdomain: DNS Domain name :param private_dir: Path", "the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp)", "None self.sitename = None self.smbconf = None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update", "def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl, domsid) for root, dirs, files", "ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert", "from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2,", "Session information :param credentials: Credentials :param lp: Loadparm context \"\"\" reg = samba.registry.Registry()", "names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private dir. :param", "\"%s%c\" % (newnbname, x) #force the length to be <16 netbiosname = newnbname[0:15]", "provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin DN:", "is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to", "= hostname + \" IN A \" + hostip gc_msdcs_ip_line = \"gc._msdcs IN", "not None: logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User:", "255) if machinepass is None: machinepass = samba.generate_random_password(128, 255) if dnspass is None:", "\\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\", ":param dnsdomain: DNS domain name of the AD domain :param policyguid: GUID of", "\"RIDALLOCATIONEND\": str(next_rid + 100 + 499), }) # This is partially Samba4 specific", "root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None,", "\"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\"", "% LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx = 0", "high: The highest USN modified by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" %", "hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend", "\"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid)", "= Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp,", "password_hash module in particular) need # to know what level of AD we", "else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb", "db object. :param sid: The domain sid. :param domaindn: The domain DN. :param", "the modules loading - we # just want to wipe and re-initialise the", "setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls on Policy folder and policies", "domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level >", "Load the database, but don's load the global schema and don't connect #", "\" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\":", "policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb", "= paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info,", "findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError:", "samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack", "address has been found. Using loopback.\") hostip = '127.0.0.1' else: hostip = hostips[0]", "DNS zone file, from the info in the current database. :param paths: paths", "socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname is None: netbiosname = hostname #", "None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression tries to ensure that we", "to the secrets database. :param session_info: Session info. :param credentials: Credentials :param lp:", "urllib import shutil import ldb from samba.auth import system_session, admin_session import samba from", "%s to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located", "dnsdomain: DNS Domain name :param hostname: Local hostname :param realm: Realm name \"\"\"", "smb.conf file and let provision generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if", "def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join", "fill == FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\":", "1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError:", "#Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if targetdir", "is not None: hostip6_base_line = \" IN AAAA \" + hostip6 hostip6_host_line =", "setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets database. :note: This function does not", "ntdsguid): \"\"\"Join a host to its own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid", "import ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import", "\"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\"", "and # we don't want to create a domain that cannot allocate rids.", ") from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB", "setntacl(lp, path, acl, domsid) for root, dirs, files in os.walk(path, topdown=False): for name", "== 0: logger.warning(\"No external IPv4 address has been found. Using loopback.\") hostip =", "read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the", "smb.conf parameters that were set # on the provision/join command line are set", "will wipe the main SAM database file! \"\"\" # Provision does not make", "have it already around # before the provisioned tree exists and we connect", "logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"),", "class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self, value): self.value = value def", "dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try: os.chmod(dns_keytab_path,", "= None self.configdn = None self.schemadn = None self.ldapmanagerdn = None self.dnsdomain =", "DNS domain name of the AD domain :param policyguid: GUID of the default", "is None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a", "del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1:", "configuration). :param path: Path of the new named.conf file. :param dnsdomain: DNS Domain", "the privileges database. :param session_info: Session info. :param credentials: Credentials :param lp: Loadparm", "want to create a domain that cannot allocate rids. if next_rid < 1000", "the existing data, which may not be stored locally but in LDAP. \"\"\"", "netbios domain at a time, # but we don't delete the old record", "tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now we", "[str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression", "dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None,", "domsid) for root, dirs, files in os.walk(path, topdown=False): for name in files: setntacl(lp,", "sid. :param domaindn: The domain DN. :param root_uid: uid of the UNIX root", ":param domaindn: The DN of the domain (ie. DC=...) :param samdb: An LDB", "setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting", "\"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path =", "domaindn, samdb, lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None,", "% smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\":", "SYSVOL_ACL on the sysvol folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for", "the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam):", "{ \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol,", "the database, not start it up try: os.unlink(samdb_path) except OSError: pass samdb =", "create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb to disk", "list. \"\"\" for name in names: try: return nssfn(name) except KeyError: pass raise", "to the provision tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors", "file for BIND\", paths.namedconf) logger.info(\"and %s for further documentation required for secure DNS", "names.domain = domain names.realm = realm names.netbiosname = netbiosname names.hostname = hostname names.sitename", "SYSVOL_ACL, str(domainsid)) for root, dirs, files in os.walk(sysvol, topdown=False): for name in files:", "the upper range of the rIDAvailablePool is 1073741823 and # we don't want", "names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid", "out a dns_update_list file\"\"\" # note that we use no variable substitution on", "code for provisioning a Samba4 server # Copyright (C) <NAME> <<EMAIL>> 2007-2010 #", "update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names,", "correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\":", "make much sense values larger than 1000000000 # as the upper range of", "if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s must match", "can't figure out the weird errors # loading an empty smb.conf gives, then", "schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None,", "ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private dir. :param ldb: LDB object.", "next_rid=1000): \"\"\"Setup a complete SAM Database. :note: This will wipe the main SAM", "in smb.conf must match chosen domain '%s'! Please remove the %s file and", "\"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception):", "install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above", "(including GSS-TSIG configuration). :param path: Path of the new named.conf file. :param dnsdomain:", "self.netbiosname = None self.domain = None self.hostname = None self.sitename = None self.smbconf", "p = os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid,", "\"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb", "'%s'!\" % (realm, netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names: Realm '%s' must", "\"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\":", "get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\", "hostname # remove forbidden chars newnbname = \"\" for x in netbiosname: if", "domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line,", "group policies (domain policy and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc)", "% ( dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc + \" unfreeze \"", "marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC)", "if dnspass is None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass is None: #", "LDIF data will be added or none (using transactions). :param ldb: LDB file", "\"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf =", "the LDIF file to load :param subst_vars: Optional variables to subsitute in LDIF.", "\\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\", "an upgradeprovision :param sam: An LDB object pointing to the sam.ldb :return: an", "NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is not a", "one IPv4 address found. Using %s.\", hostip) if serverrole is None: serverrole =", "names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up", "provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: #", "entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]:", "is None: configdn = \"CN=Configuration,\" + rootdn if schemadn is None: schemadn =", "samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\"", "(backend_credentials is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"),", "does not exist in this schema raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb,", "lp): \"\"\"Set the ACL for the sysvol share and the subfolders :param samdb:", "a list of possibilities. :param nssfn: NSS Function to try (should raise KeyError", "netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] #", "Domain name :param domaindn: DN of the Domain :param hostip: Local IPv4 IP", "str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"),", "\"objectGUID: %s\\n-\" % domainguid else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"),", "'%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname = netbiosname.lower() # We", "is None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")):", "path: Path to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def", "by this upgrade :param high: The highest USN modified by this upgrade\"\"\" tab", "None: os.system(rndc + \" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write", "the default paths for provisioning. :param lp: Loadparm context. :param dnsdomain: DNS Domain", "any existing one or appended (default) \"\"\" tab = [] if not replace:", "# \"\"\"Functions for setting up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64", "not be equal to short host name '%s'!\" % (domain, netbiosname)) else: domain", "configdn is None: configdn = \"CN=Configuration,\" + rootdn if schemadn is None: schemadn", "domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole,", "session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account found\") def", "session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param path:", "import grp import logging import time import uuid import socket import urllib import", "\\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def", "db :param netlogon: Physical path for the netlogon folder :param sysvol: Physical path", "by this upgrade :param replace: A boolean indicating if the range should replace", "assert netbiosname is not None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname)", "logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out a", "always removes the local SAM LDB file. The erase parameter controls whether to", "for no controls \"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls)", "object. :param ldif_path: LDIF file path. :param subst_vars: Optional dictionary with substitution variables.", "ProvisioningError(\"guess_names: Realm '%s' must not be equal to netbios hostname '%s'!\" % (realm,", "None self.ldapmanagerdn = None self.dnsdomain = None self.realm = None self.netbiosname = None", "raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to netbios hostname '%s'!\" %", "attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path", "rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None,", "= None self.dns_keytab = None self.dns = None self.winsdb = None self.private_dir =", "backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\":", "specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding", "assert isinstance(domainguid, str) if hostip6 is not None: hostip6_base_line = \" IN AAAA", "run SAMBA 4 with a next_rid of %u, \" % (next_rid) error +=", "Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright", "tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts", "None: # Make a new, random password between Samba and it's LDAP server", "except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths", "IP :param hostname: Local hostname :param realm: Realm name :param domainguid: GUID of", "\"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\"", "of policy given its guid. :param sysvolpath: Path to the sysvol folder :param", "up IPv4 addresses\") hostips = samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No external", "nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\": # Set up group policies", "biggest USN present in the provision :param samdb: A LDB object pointing to", "dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make a", "path to the provision tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) #", "= os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir,", "logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"),", "backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the", "\\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\", "def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private dir. :param ldb:", "logger.info(\"Reopening sam.ldb with new schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb =", "be # replicated with DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6,", "= \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line =", "have been modified since last provision. :param samdb: An LDB object connect to", "setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting", "if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials,", "\\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn,", "names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain =", "= dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp,", "x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) # force", "if backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid", "next time logger.info(\"Use later the following commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped)", "adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None,", "on the original in EJS: # Copyright (C) <NAME> <<EMAIL>> 2005 # #", "setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn})", "\" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is", "object on the SAM db :param netlogon: Physical path for the netlogon folder", "at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if paths.sysvol is", "paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once", "published by # the Free Software Foundation; either version 3 of the License,", "DN. :param root_uid: uid of the UNIX root user. :param nobody_uid: uid of", "has been found. Using loopback.\") hostip = '127.0.0.1' else: hostip = hostips[0] if", "samba.auth import system_session, admin_session import samba from samba import ( Ldb, check_all_substituted, in_source_tree,", "tab = [] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE,", "does not have a [sysvol] share, but you\" \" are configuring a DC.\")", "= [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for", "located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\", "file containing zone statements suitable for inclusion in a named.conf file (including GSS-TSIG", "{ \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except", "FILL_DRS: return samdb samdb.transaction_start() try: # Set the domain functionality levels onto the", "container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) #", "lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if targetdir is not None: privdir =", "Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult()", "str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), {", "domainguid: GUID of the domain. :param ntdsguid: GUID of the hosts nTDSDSA record.", "the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if", "to check. :return: Value return by first names list. \"\"\" for name in", ":param path: Path to the registry database :param session_info: Session information :param credentials:", "is None: logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp, False) if len(hostips) ==", "keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain,", "to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger,", "at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if not os.path.isdir(paths.netlogon):", "by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list,", "uid of the UNIX root user. :param nobody_uid: uid of the UNIX nobody", "and other important objects # \"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl", "\"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p", "private dir. :param ldb: LDB file to import data into :param ldif_path: Path", "lp.get(\"netbios name\") if netbiosname is None: netbiosname = hostname # remove forbidden chars", "root, dirs, files in os.walk(sysvol, topdown=False): for name in files: if canchown: os.chown(os.path.join(root,", "os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir,", "session_info, lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap", "gid of the UNIX users group. :param wheel_gid: gid of the UNIX wheel", "\"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name),", "samba.generate_random_password(128, 255) if ldapadminpass is None: # Make a new, random password between", "sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip is None: logger.info(\"Looking", "root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\",", "software; you can redistribute it and/or modify # it under the terms of", "realm: Realm name :param dnsdomain: DNS Domain name :param private_dir: Path to private", "= paths result.lp = lp result.samdb = samdb return result def provision_become_dc(smbconf=None, targetdir=None,", "return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None,", "ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb,", "level (2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level # Also", "domain, lp.configfile)) if domaindn is None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if", "else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None:", "invocationid is None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir,", "from the # DB samdb.connect(path) if fill == FILL_DRS: return samdb samdb.transaction_start() try:", "{\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying", "dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make a zone", "OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode,", "was not specified in supplied %s. Please remove the smb.conf file and let", "DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns,", "how slapd must be # started next time logger.info(\"Use later the following commandline", "\"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we use no variable substitution on this", "\\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\", "4 on a domain and forest function level which itself is higher than", "100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499), }) # This is partially Samba4", "\"restructuredText\" from base64 import b64encode import os import re import pwd import grp", "\"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn,", "if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if", "Path to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp,", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "\"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\":", "os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if targetdir is not None: privdir", "= [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())]", "targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass,", "role=%s' in %s must match chosen server role '%s'! Please remove the smb.conf", "netbiosname)) else: domain = netbiosname if domaindn is None: domaindn = \"DC=\" +", "is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry):", "program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a Samba configuration.\"\"\"", "check_install(lp, session_info, credentials): \"\"\"Check whether the current install seems ok. :param lp: Loadparm", "os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\",", "in files: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid))", "replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in", "gid of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid)", "to modify, # because that would delete the keytab and previous password. res", "{ \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic provision", "based on a couple of basic settings. \"\"\" assert smbconf is not None", "GNU General Public License for more details. # # You should have received", "logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain,", "and re-initialise the database, not start it up try: os.unlink(samdb_path) except OSError: pass", "on the sysvol folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root,", "'users', 'other', 'staff']) if wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid", "there isn't one there already if os.path.exists(smbconf): # if Samba Team members can't", ":param sysvol: Physical path for the sysvol folder :param dnsdomain: The DNS name", "\"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec)", "or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not", ":param dnsdomain: DNS name of the AD domain :param guid: The GUID of", "if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden", "= \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file):", "subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private dir. :param ldb: LDB file to", "\"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\":", "\\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\", "ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn = None self.configdn = None self.schemadn", "hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out a DNS zone file, from", "return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by a provision or", "self.hkpd = None self.hkpt = None self.samdb = None self.idmapdb = None self.secrets", "domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None,", "remove the smb.conf file and let provision generate it\" % lp.configfile) if lp.get(\"realm\").upper()", "setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn,", "of the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if hostip6 is not", "security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm =", "Physical path for the sysvol folder :param dnsdomain: The DNS name of the", "for name in dirs: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name),", "scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified", "context \"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg", "it under the terms of the GNU General Public License as published by", "the %s file and let provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if", "= [ 'HOST/%s' % shortname ] if secure_channel_type == SEC_CHAN_BDC and dnsname is", "don't connect # quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False,", "setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF here was created", "bind_gid if hostip is None: logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp, False)", "you can redistribute it and/or modify # it under the terms of the", "hostip = hostips[0] if len(hostips) > 1: logger.warning(\"More than one IPv4 address found.", "= \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt =", "paths.spn_update_list, None) if paths.bind_gid is not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1,", "setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\":", "This field is used to track range of USN modified by provision and", "domain name '%s'!\" % (realm, domain)) if rootdn is None: rootdn = domaindn", "1073741823 and # we don't want to create a domain that cannot allocate", "b64encode import os import re import pwd import grp import logging import time", "\"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) })", "sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf file based on a couple of", "= FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port,", "if not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p,", "dnsdomain: DNS Domain name :param private_dir: Path to private directory :param keytab_name: File", "invocationid logger.info(\"Setting up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\":", "\"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\"", "= [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"] =", "msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\",", "ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger,", "bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None if targetdir is not", "msDS-SupportedEncryptionTypes into the DB # In future, this might be determined from some", "names = ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn names.configdn = configdn names.schemadn", "and the policy folders beneath. :param sysvol: Physical path for the sysvol folder", "Realm name :param domainguid: GUID of the domain. :param ntdsguid: GUID of the", "(at your option) any later version. # # This program is distributed in", "os.path.join(root, name), acl, domsid) for name in dirs: setntacl(lp, os.path.join(root, name), acl, domsid)", "names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain =", "rootdn if schemadn is None: schemadn = \"CN=Schema,\" + configdn if sitename is", "Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, })", "x) # force the length to be <16 netbiosname = newnbname[0:15] assert netbiosname", "not None domain = domain.upper() assert realm is not None realm = realm.upper()", "= ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return the biggest", "share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths,", "None self.hklm = None self.hkcu = None self.hkcr = None self.hku = None", "IPv4 address found. Using %s.\", hostip) if serverrole is None: serverrole = lp.get(\"server", "GSS-TSIG configuration). :param paths: all paths :param realm: Realm name :param dnsdomain: DNS", "realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen realm '%s'! Please remove", "# http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if", "estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this attribute does", "os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns,", "not specified in supplied %s. Please remove the smb.conf file and let provision", "%s for further documentation required for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs =", "= 0 p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0])", "security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\", "We use options=[\"modules:\"] to stop the modules loading - we # just want", "else: domain = netbiosname if domaindn is None: domaindn = \"DC=\" + netbiosname", "provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise", "in os.walk(path, topdown=False): for name in files: setntacl(lp, os.path.join(root, name), acl, domsid) for", "self.schemadn = None self.ldapmanagerdn = None self.dnsdomain = None self.realm = None self.netbiosname", "\"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname", "None: backend_type = \"ldb\" sid_generator = \"internal\" if backend_type == \"fedora-ds\": sid_generator =", "for provisioning. :param lp: Loadparm context. :param dnsdomain: DNS Domain name \"\"\" paths", "to its own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is not None: ntdsguid_line", "\"\"\"Setup the SamDB rootdse. :param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), {", "the smb.conf file and let provision generate it\" % lp.configfile) if lp.get(\"realm\").upper() !=", "self.realm = None self.netbiosname = None self.domain = None self.hostname = None self.sitename", "in EJS: # Copyright (C) <NAME> <<EMAIL>> 2005 # # This program is", "realm or netbios domain at a time, # but we don't delete the", "to know what level of AD we are emulating. # These will be", "hostips[0] if len(hostips) > 1: logger.warning(\"More than one IPv4 address found. Using %s.\",", "\"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info,", "result = ProvisionResult() result.domaindn = domaindn result.paths = paths result.lp = lp result.samdb", "names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\":", "return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm = None self.hkcu", "controller\": # Set up group policies (domain policy and domain controller # policy)", "valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain = lp.get(\"realm\") if dnsdomain is", "sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn names.configdn = configdn", "the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir,", "dictionary with substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb,", "is None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise", "names.domaindn = domaindn names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" +", "backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type", "dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf =", "it without any values that are the default # this ensures that any", "domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line,", "ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if", "IP :param hostip6: Local IPv6 IP :param hostname: Local hostname :param realm: Realm", "setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>,", "transactions). :param ldb: LDB file to import into. :param ldif_path: Path to the", "serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False,", "container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\":", "1000000000: error = \"You want to run SAMBA 4 with a next_rid of", "(domain policy and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon,", "__init__(self): self.rootdn = None self.domaindn = None self.configdn = None self.schemadn = None", "guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if not", "context :return: LDB handle for the created secrets database \"\"\" if os.path.exists(path): os.unlink(path)", "root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings for sam names to unix", "str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL", "= setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend,", "on the sysvol/<dnsname>/Policies folder and the policy folders beneath. :param sysvol: Physical path", "get_max_usn(samdb,basedn): \"\"\" This function return the biggest USN present in the provision :param", "problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] =", "\"\"\" try: os.chown(sysvol, -1, gid) except OSError: canchown = False else: canchown =", "root_uid = findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users", "and let provision generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole ==", "paths result.lp = lp result.samdb = samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None,", "schema = Schema(domainsid, schemadn=names.schemadn) # Load the database, but don's load the global", "if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this attribute does not", "create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a file containing zone statements suitable", "__docformat__ = \"restructuredText\" from base64 import b64encode import os import re import pwd", "credentials: Credentials :param lp: Loadparm context \"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path,", "%s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\":", "GUID of the domain. :param ntdsguid: GUID of the hosts nTDSDSA record. \"\"\"", "IPv4 address has been found. Using loopback.\") hostip = '127.0.0.1' else: hostip =", "private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration include file for BIND\", paths.namedconf)", "in dirs: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid))", "\"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\"", "e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn =", "\"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\":", "raise ProvisioningError(error) # ATTENTION: Do NOT change these default values without discussion with", "to chown %s to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin", "work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes the database setup_samdb_partitions(path,", "slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn", "-1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls on Policy folder", "source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc import security from samba.dcerpc.misc", "paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a file containing zone", "to import into. :param ldif_path: Path to the LDIF file. :param subst_vars: Dictionary", ":return: an integer corresponding to the highest USN modified by (upgrade)provision, 0 is", "if serverrole == \"domain controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf does not", "'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm,", "os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir))", "from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import", "empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise", ":param root_uid: uid of the UNIX root user. :param nobody_uid: uid of the", "the length to be <16 netbiosname = newnbname[0:15] assert netbiosname is not None", "policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path):", "names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\")", "canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in", "in the provision :param samdb: A LDB object pointing to the sam.ldb :param", "\"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\":", "policyguid = policyguid.upper() if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper()", "dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to a secrets database. :param secretsdb: Ldb", "= os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\")", "self.keytab = None self.dns_keytab = None self.dns = None self.winsdb = None self.private_dir", "in the private dir. :param ldb: LDB object. :param ldif_path: LDIF file path.", "dnsname is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"]", "for this SID, realm or netbios domain at a time, # but we", ":param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\":", "= \"dc\" elif serverrole == \"member server\": smbconfsuffix = \"member\" elif serverrole ==", "smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None: smbconf = samba.param.default_path() if", "os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path", "(enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this attribute", "sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "pwd import grp import logging import time import uuid import socket import urllib", "an integer corresponding to the highest USN modified by (upgrade)provision, 0 is this", "DN of the domain (ie. DC=...) :param samdb: An LDB object on the", "= [str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex", "configdn = \"CN=Configuration,\" + rootdn if schemadn is None: schemadn = \"CN=Schema,\" +", "user/group in %r\" % names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid =", "krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete", "names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb,", "\"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp,", "provision_backend.init() provision_backend.start() # only install a new shares config db if there is", "def __init__(self): self.rootdn = None self.domaindn = None self.configdn = None self.schemadn =", "dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm =' was not specified in", "b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths,", "fill == FILL_DRS: return samdb samdb.transaction_start() try: # Set the domain functionality levels", "group. :param wheel_gid: gid of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid)", "[] idx = 0 p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab =", "paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\")", "not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), {", "the AD domain :param guid: The GUID of the policy :return: A string", "database :param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb,", "if serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except", "provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path,", "paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None,", "= None self.dns = None self.winsdb = None self.private_dir = None class ProvisionNames(object):", "ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start() # only install a new shares", "\"\" if sid_generator == \"internal\": sid_generator_line = \"\" else: sid_generator_line = \"sid generator", "\"DC=\" + netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise", "the secrets database :param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError:", "= os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc):", "Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\":", "paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb =", "DC=foo, DC=bar) :return: The biggest USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"],", "is stored without path prefix for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab", "domain is None: # This will, for better or worse, default to 'WORKGROUP'", "= \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd =", ":param machinepass: Machine password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"]", "if domainsid is None: domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt", "= setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp)", "path: path to the idmap database :param session_info: Session information :param credentials: Credentials", "shares config db if there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\")", "database. :note: This will wipe the Sam Database! :note: This function always removes", "name), acl, domsid) for name in dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def", "LDIF here was created when the Schema object was constructed logger.info(\"Setting up sam.ldb", "hostip_base_line = \" IN A \" + hostip hostip_host_line = hostname + \"", "the GNU General Public License # along with this program. If not, see", "not be equal to short domain name '%s'!\" % (realm, domain)) if rootdn", "\"CN=Schema,\" + configdn if sitename is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn =", "b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass,", "paths.sysvol is None: logger.info(\"Existing smb.conf does not have a [sysvol] share, but you\"", "supplied %s!\" % lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") ==", "database. :param paths: paths object :param dnsdomain: DNS Domain name :param domaindn: DN", "to the sam.ldb :return: an integer corresponding to the highest USN modified by", "\"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm,", "backend code for provisioning a Samba4 server # Copyright (C) <NAME> <<EMAIL>> 2007-2010", "( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc", "\"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\"", "lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\" if provision_backend.type is not \"ldb\":", "\"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\":", "netbiosname = newnbname[0:15] assert netbiosname is not None netbiosname = netbiosname.upper() if not", "provision generate it\" % lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in", "= sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return names def", "whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if", "schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip is", "maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration", "hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" + hostip6 else: hostip6_base_line = \"\"", "database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp)", "sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf lp.load(smbconf) # and", "dnsname = None shortname = netbiosname.lower() # We don't need to set msg[\"flatname\"]", "\"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname,", "+ hostip gc_msdcs_ip_line = \"gc._msdcs IN A \" + hostip else: hostip_base_line =", "LDAP backend type selected\") provision_backend.init() provision_backend.start() # only install a new shares config", "if Samba Team members can't figure out the weird errors # loading an", "netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\":", "Value return by first names list. \"\"\" for name in names: try: return", "[res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el", "not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a Samba configuration.\"\"\" __docformat__ =", "paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol", "not None if paths.sysvol is None: logger.info(\"Existing smb.conf does not have a [sysvol]", "is not None # We use options=[\"modules:\"] to stop the modules loading -", "domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def", "fixed into the database via the database # modifictions below, but we need", "the correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn,", "role' not specified in supplied %s!\" % lp.configfile) serverrole = serverrole.lower() realm =", "serverrole == \"domain controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf does not have", "paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None:", "names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths", "and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not None:", "ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this", "Copyright (C) <NAME> <<EMAIL>> 2005 # # This program is free software; you", "hostname: Local hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain,", "# The LDIF here was created when the Schema object was constructed logger.info(\"Setting", "samdb samdb.transaction_start() try: # Set the domain functionality levels onto the database. #", "\"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\")", "names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\":", "== \"\": raise ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\", lp.configfile) dnsdomain =", "\\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl,", "up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap =", "dnsdomain): \"\"\"Set the default paths for provisioning. :param lp: Loadparm context. :param dnsdomain:", "if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid)", "A \" + hostip gc_msdcs_ip_line = \"gc._msdcs IN A \" + hostip else:", "backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema,", "= findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None if", "samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS", "serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\"", "if targetdir is not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is", "Loadparm context :return: LDB handle for the created secrets database \"\"\" if os.path.exists(path):", "realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname =", "None: logger.info(\"Existing smb.conf does not have a [sysvol] share, but you\" \" are", "hostip6 hostip6_host_line = hostname + \" IN AAAA \" + hostip6 gc_msdcs_ip6_line =", "of naming contexts and other important objects # \"get_schema_descriptor\" is located in \"schema.py\"", "required for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb,", "it and/or modify # it under the terms of the GNU General Public", "+ 100 + 499), }) # This is partially Samba4 specific and should", "hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out a DNS zone file, from the", "load :param subst_vars: Optional variables to subsitute in LDIF. :param nocontrols: Optional list", "\"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb", "to the secrets database :param machinepass: Machine password \"\"\" attrs = [\"whenChanged\", \"secret\",", ":param hostip: Local IPv4 IP :param hostip6: Local IPv6 IP :param hostname: Local", "as published by # the Free Software Foundation; either version 3 of the", "object was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"])", "folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None,", "on the SAM db :param lp: an LP object \"\"\" # Set ACL", "setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A", "SAM db :param lp: an LP object \"\"\" # Set ACL for GPO", "# In future, this might be determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES)", "\"internal\" assert domain is not None domain = domain.upper() assert realm is not", "names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif", "\"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users', 'other', 'staff']) if wheel is None:", "= [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)]", "\\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None,", "\"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\"", "\"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\":", "DNS specific bits to a secrets database. :param secretsdb: Ldb Handle to the", "been modified since last provision. :param samdb: An LDB object connect to sam.ldb", "OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind gid %u\", dns_keytab_path,", "up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn})", "}) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path of policy given its", "1: raise ProvisioningError(\"No administrator account found\") def findnss(nssfn, names): \"\"\"Find a user or", "= \"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line =", "lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup", "= None self.hkcu = None self.hkcr = None self.hku = None self.hkpd =", "to show how slapd must be # started next time logger.info(\"Use later the", "except OSError: canchown = False else: canchown = True # Set the SYSVOL_ACL", ":param basedn: A string containing the base DN of the provision (ie. DC=foo,", "domain :param domainsid: The SID of the domain :param domaindn: The DN of", "the local SAM LDB file. The erase parameter controls whether to erase the", "share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up", "raise ProvisioningError(\"guess_names: Domain '%s' must not be equal to short host name '%s'!\"", "\"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100 +", "= os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku", "= \"gc._msdcs IN AAAA \" + hostip6 else: hostip6_base_line = \"\" hostip6_host_line =", "\\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\", "domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid", "files: setntacl(lp, os.path.join(root, name), acl, domsid) for name in dirs: setntacl(lp, os.path.join(root, name),", "2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # # Based on the original", "\"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\":", "implementation. # backend code for provisioning a Samba4 server # Copyright (C) <NAME>", "up try: os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line", "start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" %", "%s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS", "== FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn,", ":param sam: An LDB object pointing to the sam.ldb :return: an integer corresponding", "new named.conf file. :param dnsdomain: DNS Domain name :param hostname: Local hostname :param", "0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba 4", ") import samba.param import samba.registry from samba.schema import Schema from samba.samdb import SamDB", "len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account found\") def findnss(nssfn, names): \"\"\"Find a", "\"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\"", "\\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\", "expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res", "\"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn())", "names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' % (", "= Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and", "def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO for a domain :param", "# only install a new shares config db if there is none if", "\\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec", "return the biggest USN present in the provision :param samdb: A LDB object", "def setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass,", "names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display", "None # We use options=[\"modules:\"] to stop the modules loading - we #", "the created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if", "guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration", "!= domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match chosen domain '%s'!", "schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb", "paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig", "realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' %", "secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not", "in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc import security from", "str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE)", "to the registry database :param session_info: Session information :param credentials: Credentials :param lp:", "-1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in dirs: if canchown:", "names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF here was created when the Schema", "self.hkcu = None self.hkcr = None self.hku = None self.hkpd = None self.hkpt", "serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if", "samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4", "in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl,", "database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir,", "os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid,", "\"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list", "set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL,", "be <16 netbiosname = newnbname[0:15] assert netbiosname is not None netbiosname = netbiosname.upper()", "setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\":", "program is distributed in the hope that it will be useful, # but", "logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid,", "distributed in the hope that it will be useful, # but WITHOUT ANY", "backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def", "os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind gid %u\" % ( dns_dir, paths.bind_gid))", "old record that we are about to modify, # because that would delete", "\"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp):", "GUID of the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if hostip6 is", "replace any existing one or appended (default) \"\"\" tab = [] if not", "connect # quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc)", "DNS Domain name \"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This", "invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its own domain.\"\"\" assert", "policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000):", "lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp):", "sysvol folder :param dnsdomain: The DNS name of the domain :param domainsid: The", "None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(),", "hostip_host_line = hostname + \" IN A \" + hostip gc_msdcs_ip_line = \"gc._msdcs", "\"\"\" assert isinstance(domainguid, str) if hostip6 is not None: hostip6_base_line = \" IN", "def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a file into a LDB handle,", "\"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"),", "the current install seems ok. :param lp: Loadparm context :param session_info: Session information", "sysvolpath: Path to the sysvol folder :param dnsdomain: DNS name of the AD", "\"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\")", "if there isn't one there already if os.path.exists(smbconf): # if Samba Team members", "None self.idmapdb = None self.secrets = None self.keytab = None self.dns_keytab = None", "names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"),", "setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a file into a LDB handle, optionally", "setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up sam.ldb", "schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database. :note: This will wipe the main", "is None: raise ProvisioningError(\"guess_names: 'server role' not specified in supplied %s!\" % lp.configfile)", "out a DNS zone file, from the info in the current database. :param", "Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account", "hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp is None: lp", "self.ldapmanagerdn = None self.dnsdomain = None self.realm = None self.netbiosname = None self.domain", "host to its own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is not None:", "name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is not a valid", "AAAA \" + hostip6 hostip6_host_line = hostname + \" IN AAAA \" +", "modify, # because that would delete the keytab and previous password. res =", "dnsdomain: The DNS name of the domain :param domainsid: The SID of the", "entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\":", "= get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN, 1) else:", "domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its own", "= samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else:", "# Now commit the secrets.ldb to disk secrets_ldb.transaction_commit() # the commit creates the", "we add servicePrincipalName # entries for the keytab code to update. spn.extend([ 'HOST/%s'", "backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid =", "\"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we use no variable substitution", "lp=lp) logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger,", "db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb,", "context :return: LDB handle for the created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets)", "DNS Domain name :param domaindn: DN of the Domain :param hostip: Local IPv4", "rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname,", "lp.get(\"private dir\") # This is stored without path prefix for the \"privateKeytab\" attribute", "except KeyError: pass for el in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg)", "None) if paths.bind_gid is not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid)", "domain '%s'! Please remove the %s file and let provision generate it\" %", "def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a file containing zone statements", "paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd", "\"\"\"Setup the partitions for the SAM database. Alternatively, provision() may call this, and", "if hostip is None: logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp, False) if", "Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username())", "domain that cannot allocate rids. if next_rid < 1000 or next_rid > 1000000000:", "\"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\"", "= [ndr_pack(domainsid)] # This complex expression tries to ensure that we don't have", "don't have more # than one record for this SID, realm or netbios", "these default values without discussion with the # team and/or release manager. They", "samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid))", "of the provision (ie. DC=foo, DC=bar) :return: The biggest USN in the provision\"\"\"", "let provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole:", "hostip else: hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir =", "of the domain. :param ntdsguid: GUID of the hosts nTDSDSA record. \"\"\" assert", "msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE,", "\\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\", "\"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths def guess_names(lp=None, hostname=None,", "hostname, realm, domainguid, ntdsguid): \"\"\"Write out a DNS zone file, from the info", "the policy :return: A string with the complete path to the policy folder", "'staff']) if wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel])", "hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm,", "following commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored", "self.winsdb = None self.private_dir = None class ProvisionNames(object): def __init__(self): self.rootdn = None", "str(int(time.time() * 1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename,", "paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir)", "or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users',", "setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add", "replace=False): \"\"\"Update the field provisionUSN in sam.ldb This field is used to track", "schemadn=names.schemadn) # Load the database, but don's load the global schema and don't", "it up try: os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"])", "let provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None: domaindn", "= SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS settings DN", "result.samdb = samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None,", "the idmap database :param session_info: Session information :param credentials: Credentials :param lp: Loadparm", "samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\"", "schema, serverrole, erase=False): \"\"\"Setup the partitions for the SAM database. Alternatively, provision() may", "if paths.sysvol is None: logger.info(\"Existing smb.conf does not have a [sysvol] share, but", "\"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self):", "None self.lp = None self.samdb = None def check_install(lp, session_info, credentials): \"\"\"Check whether", "at %s\", paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown()", "Local hostname :param realm: Realm name :param domainguid: GUID of the domain. :param", "add servicePrincipalName # entries for the keytab code to update. spn.extend([ 'HOST/%s' %", "out if the field have been modified since last provision. :param samdb: An", "caution, this wipes all existing data! \"\"\" if domainsid is None: domainsid =", "(domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn,", "to sam.ldb :param low: The lowest USN modified by this upgrade :param high:", "default values without discussion with the # team and/or release manager. They have", "root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\": # Set up group", "keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path):", "domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def", "setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in dirs: if canchown: os.chown(os.path.join(root, name),", "if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain = lp.get(\"realm\") if", "provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip is None: logger.info(\"Looking up IPv4 addresses\")", "invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names,", "provision :param samdb: A LDB object pointing to the sam.ldb :param basedn: A", "policyguid_dc): \"\"\"Create the default GPO for a domain :param sysvolpath: Physical path for", "IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB", "wipe the main SAM database file! \"\"\" # Provision does not make much", "gc_msdcs_ip6_line, }) # note that we use no variable substitution on this file", "\"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb,", "names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\"", "machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\": if", "not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema =", "realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line", "or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\")", "keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a secrets database. :param secretsdb:", "samba.param import samba.registry from samba.schema import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS =", "idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb, session_info,", "import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE", "serverrole = lp.get(\"server role\") if serverrole is None: raise ProvisioningError(\"guess_names: 'server role' not", "logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn =", "names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn})", "chars newnbname = \"\" for x in netbiosname: if x.isalnum() or x in", "paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt", "str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\": # Set", "# This complex expression tries to ensure that we don't have more #", "\"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid),", "raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to hostname '%s'!\" % (realm,", "\"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL:", "setting up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import b64encode import", "USN modified by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low, high)) delta", "samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No", "p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx", "LDB handle for the created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path =", "not lp.get(\"posix:eadb\"): if targetdir is not None: privdir = os.path.join(targetdir, \"private\") else: privdir", "the current database. :param paths: paths object :param dnsdomain: DNS Domain name :param", "all paths :param realm: Realm name :param dnsdomain: DNS Domain name :param private_dir:", "of the new named.conf file. :param realm: Realm name :param dnsdomain: DNS Domain", "\"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must", "up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), # seconds ->", "not None: privatedir_line = \"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line =", "\"\" if hostip is not None: hostip_base_line = \" IN A \" +", "except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind gid %u\"", "= getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid, domainguid, policyguid,", ":param nssfn: NSS Function to try (should raise KeyError if not found) :param", "it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try:", "setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc import security from samba.dcerpc.misc import (", "{ \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\":", "else: spn = [ 'HOST/%s' % shortname ] if secure_channel_type == SEC_CHAN_BDC and", "# policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn,", "security.dom_sid(domainsid) # create/adapt the group policy GUIDs # Default GUID for default policy", "netbiosname, sitename, configdn) return names def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\",", "sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings for sam names", "DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path to", "domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a secrets", "\"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\":", "name in files: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL,", "address found. Using %s.\", hostip) if serverrole is None: serverrole = lp.get(\"server role\")", "realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\",", "= ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def", "program is free software; you can redistribute it and/or modify # it under", "up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\":", "DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except OSError: canchown = False else: canchown", "to the caller to do this job. :param path: Path to the secrets", "x in netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" %", "\"private\")) lockdir_line = \"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else:", "the physical path of policy given its guid. :param sysvolpath: Path to the", "not None: # we are a domain controller then we add servicePrincipalName #", "secrets.ldb to disk secrets_ldb.transaction_commit() # the commit creates the dns.keytab, now chown it", "None: domaindn = \"DC=\" + netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper()", "= \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if hostip is not None:", "get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb,", "and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now we can connect", "\"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf", "options=[\"modules:\"] to stop the modules loading - we # just want to wipe", "object :param dnsdomain: DNS Domain name :param domaindn: DN of the Domain :param", "Physical path for the sysvol folder :param gid: The GID of the \"Domain", "{ \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf,", "\\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\", "must not be equal to hostname '%s'!\" % (realm, hostname)) if netbiosname.upper() ==", ":param samdb: An LDB object connect to sam.ldb :param low: The lowest USN", "setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass,", "on Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def", "ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp,", "def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to", "function always removes the local SAM LDB file. The erase parameter controls whether", "DB - the schema won't be loaded from the # DB samdb.connect(path) if", "as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) #", "\\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return", "None or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\",", "for name in dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid,", "should have received a copy of the GNU General Public License # along", "dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA 4 on a domain", "(dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] =", "file and let provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower()", "names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower())", "secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb to disk secrets_ldb.transaction_commit() # the commit", "elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri)", "upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn =", ":param samdb: A LDB object pointing to the sam.ldb :param basedn: A string", "data is None or data == \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir,", "dnsdomain, private_dir): \"\"\"Write out a file containing zone statements suitable for inclusion in", "Ldb Handle to the secrets database :param machinepass: Machine password \"\"\" attrs =", "{ \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, })", "gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL for the sysvol share and", "we don't delete the old record that we are about to modify, #", "hostname.upper() if serverrole is None: serverrole = \"standalone\" assert serverrole in (\"domain controller\",", "os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install", "logger.info(\"Failed to chown %s to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the", "None) # and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is", "samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn,", "samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No external IPv4 address has been found.", "provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try:", "next_rid < 1000 or next_rid > 1000000000: error = \"You want to run", "= False else: canchown = True # Set the SYSVOL_ACL on the sysvol", "raise ProvisioningError(\"guess_names: 'realm =' was not specified in supplied %s. Please remove the", "ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this", "\"\"\"Create the default GPO for a domain :param sysvolpath: Physical path for the", "# the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) #", "rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>,", "names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self", "serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if hostname is None: hostname =", "before the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path)", "rootdn names.domaindn = domaindn names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\"", "ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self, value): self.value = value def __str__(self):", "domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) #", "samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add", "logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: # now", "(\"domain controller\", \"member server\", \"standalone\") if serverrole == \"domain controller\": smbconfsuffix = \"dc\"", "stored locally but in LDAP. \"\"\" assert session_info is not None # We", "logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No", "the SamDB rootdse. :param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\":", "name \"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This is stored", "is None: schema = Schema(domainsid, schemadn=names.schemadn) # Load the database, but don's load", "nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None,", "string containing the base DN of the provision (ie. DC=foo, DC=bar) :return: The", "logger.info(\"Use later the following commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline", "secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a secrets database. :param secretsdb: Ldb Handle", "file! \"\"\" # Provision does not make much sense values larger than 1000000000", "# Set the domain functionality levels onto the database. # Various module (the", "\"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\"", "path to the idmap database :param session_info: Session information :param credentials: Credentials :param", "setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names)", "provision error.\"\"\" def __init__(self, value): self.value = value def __str__(self): return \"ProvisioningError: \"", "\\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\", "create a domain that cannot allocate rids. if next_rid < 1000 or next_rid", ":param dnsdomain: DNS Domain name :param private_dir: Path to private directory :param keytab_name:", "logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type", "(next_rid) error += \"the valid range is %u-%u. The default is %u.\" %", "\"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\"", "setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up", "a user or group from a list of possibilities. :param nssfn: NSS Function", "specified in supplied %s. Please remove the smb.conf file and let provision generate", "used afterward by next provision to figure out if the field have been", "'server role=%s' in %s must match chosen server role '%s'! Please remove the", "Load the schema from the one we computed earlier samdb.set_schema(schema) # Set the", "Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp)", "corresponding to the highest USN modified by (upgrade)provision, 0 is this value is", "Dictionary with substitution variables. \"\"\" assert ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb,", "Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and backend_credentials.authentication_requested()):", "samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path,", "targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None,", "import os import re import pwd import grp import logging import time import", "and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid,", "gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir,", "Realm name :param dnsdomain: DNS Domain name :param private_dir: Path to private directory", "schema and don't connect # quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials,", "wheel_gid=wheel_gid) if serverrole == \"domain controller\": # Set up group policies (domain policy", "str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain,", "file to import data into :param ldif_path: Path of the LDIF file to", "if the field have been modified since last provision. :param samdb: An LDB", "private directory :param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path,", "\"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration", "\"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return", "msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not None:", "\"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\":", "lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None: privatedir_line = \"private", "display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif)", "\\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\", "policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if", "the policy folders beneath. :param sysvol: Physical path for the sysvol folder :param", "Please remove the smb.conf file and let provision generate it\" % lp.configfile) if", "based SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\",", "subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private dir. :param ldb: LDB object. :param", "dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration include file for BIND\",", "at # \"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None:", "important objects # \"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\"", "= os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path)", "samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN in sam.ldb This field", "domain (ie. DC=...) :param samdb: An LDB object on the SAM db :param", "wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid", "% dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain,", "setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"),", "create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid,", "domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes the database setup_samdb_partitions(path, logger=logger,", "secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path)", "import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from", "domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False,", "a [sysvol] share, but you\" \" are configuring a DC.\") logger.info(\"Please either remove", "paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb", "not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind gid %u\" % ( dns_dir,", "paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt", "DNS Domain name :param private_dir: Path to private directory :param keytab_name: File name", "LDB object on the SAM db :param netlogon: Physical path for the netlogon", "Schema object was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data,", "None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\",", "\"\": raise ProvisioningError(\"guess_names: 'realm =' was not specified in supplied %s. Please remove", "higher than its actual DC function level (2008_R2). This won't work!\") domainFunctionality =", "logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole,", "\"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by a", "policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID", "that are the default # this ensures that any smb.conf parameters that were", "domain = domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf", "current install seems ok. :param lp: Loadparm context :param session_info: Session information :param", "aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False,", "gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we use no variable substitution on", "provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for provisioning. :param lp: Loadparm context. :param", "Domain :param hostip: Local IPv4 IP :param hostip6: Local IPv6 IP :param hostname:", "\"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\"", "import time import uuid import socket import urllib import shutil import ldb from", "%s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if paths.sysvol is None:", ":param realm: Realm name :param domainguid: GUID of the domain. :param ntdsguid: GUID", "# force the length to be <16 netbiosname = newnbname[0:15] assert netbiosname is", "socket import urllib import shutil import ldb from samba.auth import system_session, admin_session import", "%s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain)", "subst_vars: Dictionary with substitution variables. \"\"\" assert ldb is not None ldb.transaction_start() try:", "we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting", "name), SYSVOL_ACL, str(domainsid)) # Set acls on Policy folder and policies folders set_gpos_acl(sysvol,", "netbiosname = hostname.upper() # remove forbidden chars newnbname = \"\" for x in", "+ netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names:", "\"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec)", ":param sysvolpath: Physical path for the sysvol folder :param dnsdomain: DNS domain name", "domaindn if configdn is None: configdn = \"CN=Configuration,\" + rootdn if schemadn is", "names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100", "= None self.schemadn = None self.ldapmanagerdn = None self.dnsdomain = None self.realm =", "os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid,", "% (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res =", "netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x)", "schema=schema) if schema is None: schema = Schema(domainsid, schemadn=names.schemadn) # Load the database,", "names.dnsdomain = dnsdomain names.domain = domain names.realm = realm names.netbiosname = netbiosname names.hostname", "by this upgrade :param high: The highest USN modified by this upgrade :param", "None: serverrole = lp.get(\"server role\") if serverrole is None: raise ProvisioningError(\"guess_names: 'server role'", "= lp.get(\"realm\") if dnsdomain is None or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm'", "OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass),", "hostname, realm): \"\"\"Write out a file containing zone statements suitable for inclusion in", "rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"),", "wipe the Sam Database! :note: This function always removes the local SAM LDB", "SAMBA 4 on a domain and forest function level which itself is higher", "}) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds ->", "and previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid),", "# Load the database, but don's load the global schema and don't connect", "<http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from", "be equal to short domain name '%s'!\" % (realm, domain)) if rootdn is", "schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP", "= None self.hkpt = None self.samdb = None self.idmapdb = None self.secrets =", "password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is", "load the global schema and don't connect # quite yet samdb = SamDB(session_info=session_info,", "import shutil import ldb from samba.auth import system_session, admin_session import samba from samba", "remove %s or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol", "DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin", "own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is not None: ntdsguid_line = \"objectGUID:", "= invocationid logger.info(\"Setting up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), {", "dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO for a domain :param sysvolpath: Physical", "dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a secrets database. :param", "not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"),", "\"standalone\") if invocationid is None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if", "0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s", "names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb", "particular) need # to know what level of AD we are emulating. #", "generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain controller\": if", "object pointing to the sam.ldb :param basedn: A string containing the base DN", "in LDAP. \"\"\" assert session_info is not None # We use options=[\"modules:\"] to", "sam.ldb :param low: The lowest USN modified by this upgrade :param high: The", "os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir,", "supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is None: serverrole = lp.get(\"server", "seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality),", "domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s", "read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb,", "policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None,", "attribute does not exist in this schema raise if serverrole == \"domain controller\":", "users group. :param wheel_gid: gid of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID,", "database, not start it up try: os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path,", "= os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir,", "(C) <NAME> <<EMAIL>> 2008-2009 # # Based on the original in EJS: #", "x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) # force the length", "\\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and the policy folders beneath. :param", "is not None: if dnsdomain is None: dnsdomain = realm.lower() dnsname = '%s.%s'", "up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality,", "this, and then populate the database. :note: This will wipe the Sam Database!", "by the correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\":", "0: logger.warning(\"No external IPv4 address has been found. Using loopback.\") hostip = '127.0.0.1'", "that were set # on the provision/join command line are set in the", "( dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc + \" unfreeze \" +", "command line are set in the resulting smb.conf f = open(smbconf, mode='w') lp.dump(f,", "are about to modify, # because that would delete the keytab and previous", "policy and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol,", "copy of the GNU General Public License # along with this program. If", "DB samdb.connect(path) if fill == FILL_DRS: return samdb samdb.transaction_start() try: # Set the", "'%s'! Please remove the smb.conf file and let provision generate it\" % (lp.get(\"realm\").upper(),", "to do this job. :param path: Path to the secrets database. :param session_info:", "is not None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain,", "names: Names to check. :return: Value return by first names list. \"\"\" for", "the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf", "samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS settings", "realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\"", "LDB file. The erase parameter controls whether to erase the existing data, which", "paths.phpldapadminconfig) logger.info(\"Once the above files are installed, your Samba4 server will be ready", "LDIF. :param nocontrols: Optional list of controls, can be None for no controls", "os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path,", "+ \" IN A \" + hostip gc_msdcs_ip_line = \"gc._msdcs IN A \"", "targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb,", "AD domain :param policyguid: GUID of the default domain policy :param policyguid_dc: GUID", "str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url =", "if serverrole is None: raise ProvisioningError(\"guess_names: 'server role' not specified in supplied %s!\"", "Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\"))", "ProvisioningError(\"You want to run SAMBA 4 on a domain and forest function level", "\"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\"", "in the hope that it will be useful, # but WITHOUT ANY WARRANTY;", "str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a", "0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid)", "\"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\"", "!= serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s must match chosen server role", "between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type", "cannot allocate rids. if next_rid < 1000 or next_rid > 1000000000: error =", "os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\"", "rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename)", "str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC", "example configuration include file for BIND\", paths.namedconf) logger.info(\"and %s for further documentation required", "POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl, domsid) for", "\\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\", "None: lp = samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb and", "netbiosname is not None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if", "sid_generator == \"internal\": sid_generator_line = \"\" else: sid_generator_line = \"sid generator = \"", "it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server", "= security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt the group policy GUIDs #", "elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid,", "policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID based SPNs ntds_dn =", "netlogon folder :param sysvol: Physical path for the sysvol folder :param gid: The", "ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution,", "name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls on Policy", "def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the partitions", "root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\")", "Names to check. :return: Value return by first names list. \"\"\" for name", "configuration suitable for Samba 4 has been \" \"generated at %s\", paths.krb5conf) if", "\"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\"", "\"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\"", "if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\"", "realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None,", "urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend =", "setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking", "os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf if there isn't one there already", "names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise", "or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\", lp.configfile)", "msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [", "ProvisionResult() result.domaindn = domaindn result.paths = paths result.lp = lp result.samdb = samdb", "DC, it should be # replicated with DNS replication create_zone_file(lp, logger, paths, targetdir,", "255) if ldapadminpass is None: # Make a new, random password between Samba", "substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the", "os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if not", "unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range", ":param path: Path to the secrets database. :param session_info: Session info. :param credentials:", "users_gid = findnss_gid([users or \"users\", 'users', 'other', 'staff']) if wheel is None: wheel_gid", "\"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\":", "\"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu =", "% domainguid else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\":", "Domain name \"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This is", "is None: serverrole = lp.get(\"server role\") if serverrole is None: raise ProvisioningError(\"guess_names: 'server", "more # than one record for this SID, realm or netbios domain at", "idx + 1 return range else: return None class ProvisionResult(object): def __init__(self): self.paths", "'%s'!\" % (domain, netbiosname)) else: domain = netbiosname if domaindn is None: domaindn", "the database. # Various module (the password_hash module in particular) need # to", "determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\"", "that cannot allocate rids. if next_rid < 1000 or next_rid > 1000000000: error", "setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding", "def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field provisionUSN in sam.ldb This field", "logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is None: schema =", "will be fixed into the database via the database # modifictions below, but", "%s must match chosen server role '%s'! Please remove the smb.conf file and", "if len(hostips) > 1: logger.warning(\"More than one IPv4 address found. Using %s.\", hostip)", "to try (should raise KeyError if not found) :param names: Names to check.", "\"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower())", "# along with this program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting", "% domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is not", "for an example configuration include file for BIND\", paths.namedconf) logger.info(\"and %s for further", "smb.conf if there isn't one there already if os.path.exists(smbconf): # if Samba Team", "= read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a", "= \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid,", "is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN", "self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was not a valid NetBIOS name.\"\"\" def", "no variable substitution on this file # the substitution is done at runtime", "LDB handle for the created secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb =", "hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path,", "str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid", "\"domain controller\": # Set up group policies (domain policy and domain controller #", "paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) #", "policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its own domain.\"\"\" assert isinstance(invocationid, str)", "hostip = '127.0.0.1' else: hostip = hostips[0] if len(hostips) > 1: logger.warning(\"More than", "setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill", "\"\"\" assert ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception:", "modified by this upgrade :param high: The highest USN modified by this upgrade", "and should be replaced by the correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"),", "<<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>>", "function does not handle exceptions and transaction on purpose, it's up to the", "credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri)", "str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if", "paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out a DNS", "to the sysvol folder :param dnsdomain: DNS name of the AD domain :param", "names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting", "range is %u-%u. The default is %u.\" % ( 1000, 1000000000, 1000) raise", "system_session, admin_session import samba from samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file,", "policy folder \"\"\" if guid[0] != \"{\": guid = \"{%s}\" % guid policy_path", "to have it already around # before the provisioned tree exists and we", "DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is None: adminpass = samba.generate_random_password(12, 32) if", "os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\",", "os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege", "this job. :param path: Path to the secrets database. :param session_info: Session info.", "stored without path prefix for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab =", "the Samba 4 and AD schema\") # Load the schema from the one", "wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None", "will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty", "pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\"", "files in os.walk(sysvol, topdown=False): for name in files: if canchown: os.chown(os.path.join(root, name), -1,", "assert domain is not None domain = domain.upper() assert realm is not None", "fSMORoleOwner entries to point at the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), {", "domainguid is not None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid else: domainguid_line =", "<<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # # Based on the", "replace: A boolean indicating if the range should replace any existing one or", "str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif", "erase parameter controls whether to erase the existing data, which may not be", "= os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\")", "shutil import ldb from samba.auth import system_session, admin_session import samba from samba import", "provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the partitions for the SAM database. Alternatively,", "\"\"\"Guess configuration settings to use.\"\"\" if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname", "# the commit creates the dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab)", "setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\":", "ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for provisioning. :param lp: Loadparm", "handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn,", "controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a file into a LDB", "the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\"", "in supplied %s. Please remove the smb.conf file and let provision generate it\"", "impersonate domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None:", "values larger than 1000000000 # as the upper range of the rIDAvailablePool is", "configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain,", "secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in", "and don't connect # quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp,", "provision (ie. DC=foo, DC=bar) :return: The biggest USN in the provision\"\"\" res =", "modified by this upgrade :param replace: A boolean indicating if the range should", "dnspass is None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass is None: # Make", "'realm' not specified in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is", "check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\")", "None: logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp, False) if len(hostips) == 0:", "\"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\":", "without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "\"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain = domain names.realm = realm names.netbiosname", "setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\":", "netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL for the sysvol", "% ( netbiosname, sitename, configdn) return names def make_smbconf(smbconf, hostname, domain, realm, serverrole,", "GUID of the default domain policy :param policyguid_dc: GUID of the default domain", "is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden chars newnbname", "(using transactions). :param ldb: LDB file to import into. :param ldif_path: Path to", "key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a secrets database. :param secretsdb: Ldb", "next_rid=next_rid) if serverrole == \"domain controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf does", "modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"]", "and dump it without any values that are the default # this ensures", "\"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\":", "Workgroup '%s' in smb.conf must match chosen domain '%s'! Please remove the %s", "lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account found\") def findnss(nssfn, names):", "if targetdir is None: os.system(rndc + \" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp,", "ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import", "\"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "targetdir is None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \"", "the terms of the GNU General Public License as published by # the", "schema\") # Load the schema from the one we computed earlier samdb.set_schema(schema) #", "but we need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\",", "Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None,", "None def check_install(lp, session_info, credentials): \"\"\"Check whether the current install seems ok. :param", "names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to a secrets", "\"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\"", "to set msg[\"flatname\"] here, because rdn_name will handle # it, and it causes", "guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp,", "\\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\", "\"netlogon\") paths.smbconf = lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None,", "provision/join command line are set in the resulting smb.conf f = open(smbconf, mode='w')", "name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm,", "lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename)", "exceptions and transaction on purpose, it's up to the caller to do this", "for sam names to unix names. :param samdb: SamDB object. :param idmap: IDmap", "= None self.samdb = None def check_install(lp, session_info, credentials): \"\"\"Check whether the current", "% (next_rid) error += \"the valid range is %u-%u. The default is %u.\"", "for Samba 4 has been \" \"generated at %s\", paths.krb5conf) if serverrole ==", "= samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def", "that we are about to modify, # because that would delete the keytab", "logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid,", "names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499),", "dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def", "will wipe the Sam Database! :note: This function always removes the local SAM", "to wipe and re-initialise the database, not start it up try: os.unlink(samdb_path) except", "a time, # but we don't delete the old record that we are", "lp result.samdb = samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None,", "for provisioning a Samba4 server # Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright", "domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if", "Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc)", "is not None: # we are a domain controller then we add servicePrincipalName", "if machinepass is None: machinepass = samba.generate_random_password(128, 255) if dnspass is None: dnspass", "= lp.get(\"server role\") if serverrole is None: raise ProvisioningError(\"guess_names: 'server role' not specified", "== \"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody", "\"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')),", "Unix SMB/CIFS implementation. # backend code for provisioning a Samba4 server # Copyright", "then we add servicePrincipalName # entries for the keytab code to update. spn.extend([", "assert session_info is not None # We use options=[\"modules:\"] to stop the modules", "os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts and other important objects # \"get_schema_descriptor\"", "realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm,", "auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS settings DN manually -", "dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir = \" +", ":param path: Path of the new named.conf file. :param realm: Realm name :param", "exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id =", "need to be smarter. # Pretend it just didn't exist --abartlet data =", "the biggest USN present in the provision :param samdb: A LDB object pointing", "\"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid =", ":param ldb: LDB file to import data into :param ldif_path: Path of the", "- we # just want to wipe and re-initialise the database, not start", "= \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute", "replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths,", "is None: logger.info(\"Existing smb.conf does not have a [sysvol] share, but you\" \"", "the policy folder \"\"\" if guid[0] != \"{\": guid = \"{%s}\" % guid", ":param samdb: An LDB object on the SAM db :param netlogon: Physical path", "realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration include file for", "<16 netbiosname = newnbname[0:15] assert netbiosname is not None netbiosname = netbiosname.upper() if", "share, but you are configuring a DC.\") logger.info(\"Please either remove %s or see", "not None: if dnsdomain is None: dnsdomain = realm.lower() dnsname = '%s.%s' %", "\\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\", "policyguid_dc.upper() if adminpass is None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass is None:", "\"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass", "default domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path)", "ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\":", "\"eadb.tdb\"))) if targetdir is not None: privatedir_line = \"private dir = \" +", "findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users', 'other', 'staff']) if wheel", "except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database. :param", "\"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\",", "from samba.dcerpc import security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb", "= samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e))", "attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try:", "descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif,", "synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now", "setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if", "of possibilities. :param nssfn: NSS Function to try (should raise KeyError if not", "ProvisioningError(\"guess_names: Domain '%s' must not be equal to short host name '%s'!\" %", "if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else:", "msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" %", "\"Domain adminstrators\" group :param domainsid: The SID of the domain :param dnsdomain: The", "super(InvalidNetbiosName, self).__init__( \"The name '%r' is not a valid NetBIOS name\" % name)", "\"dc\" elif serverrole == \"member server\": smbconfsuffix = \"member\" elif serverrole == \"standalone\":", "now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not", "the Domain :param hostip: Local IPv4 IP :param hostip6: Local IPv6 IP :param", "(including GSS-TSIG configuration). :param path: Path of the new named.conf file. :param realm:", ":param session_info: Session info. :param credentials: Credentials :param lp: Loadparm context :return: LDB", "serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator,", "the UNIX users group. :param wheel_gid: gid of the UNIX wheel group. \"\"\"", "db if there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb =", "the SYSVOL_ACL on the sysvol folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid))", "from base64 import b64encode import os import re import pwd import grp import", "KeyError if not found) :param names: Names to check. :return: Value return by", "%s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are installed, your Samba4 server", "GSS-TSIG configuration). :param path: Path of the new named.conf file. :param realm: Realm", "= ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN", "1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do NOT change these default values", "value is used afterward by next provision to figure out if the field", "\"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path =", "in (\"domain controller\", \"member server\", \"standalone\") if serverrole == \"domain controller\": smbconfsuffix =", "None: schema = Schema(domainsid, schemadn=names.schemadn) # Load the database, but don's load the", "commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under:", "to import data into :param ldif_path: Path of the LDIF file to load", "current database. :param paths: paths object :param dnsdomain: DNS Domain name :param domaindn:", "of the Domain :param hostip: Local IPv4 IP :param hostip6: Local IPv6 IP", "policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None,", "that any smb.conf parameters that were set # on the provision/join command line", "file # the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None)", "__init__(self, value): self.value = value def __str__(self): return \"ProvisioningError: \" + self.value class", "whether to erase the existing data, which may not be stored locally but", "name of the domain :param domainsid: The SID of the domain :param domaindn:", "not have a [netlogon] share, but you are configuring a DC.\") logger.info(\"Please either", "domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None,", "% ( 1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do NOT change these", "targetdir, sid_generator, useeadb, lp=lp) if lp is None: lp = samba.param.LoadParm() lp.load(smbconf) names", "nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users', 'other', 'staff'])", "if domain is None: # This will, for better or worse, default to", "in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is None: serverrole =", "\"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str)", "samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with", "The SID of the domain :param dnsdomain: The DNS name of the domain", "to be <16 netbiosname = newnbname[0:15] assert netbiosname is not None netbiosname =", "None shortname = netbiosname.lower() # We don't need to set msg[\"flatname\"] here, because", "ProvisioningError(\"guess_names: Realm '%s' must not be equal to hostname '%s'!\" % (realm, hostname))", "policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is None: adminpass = samba.generate_random_password(12,", "= \" IN A \" + hostip hostip_host_line = hostname + \" IN", "Using loopback.\") hostip = '127.0.0.1' else: hostip = hostips[0] if len(hostips) > 1:", "samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make a zone file on the", "{ \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid),", "% (domain, netbiosname)) else: domain = netbiosname if domaindn is None: domaindn =", "100 + 499), }) # This is partially Samba4 specific and should be", "\"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb,", "else: domainsid = security.dom_sid(domainsid) # create/adapt the group policy GUIDs # Default GUID", ":return: LDB handle for the created secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb", "netbiosname if domaindn is None: domaindn = \"DC=\" + netbiosname if not valid_netbios_name(domain):", "import socket import urllib import shutil import ldb from samba.auth import system_session, admin_session", "policy :return: A string with the complete path to the policy folder \"\"\"", "= secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg", "import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from", "base DN of the provision (ie. DC=foo, DC=bar) :return: The biggest USN in", "the provision tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of", "None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a file containing zone statements", "dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make", "\\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\", "lp: Loadparm context. :param dnsdomain: DNS Domain name \"\"\" paths = ProvisionPaths() paths.private_dir", "= os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir,", "the # GNU General Public License for more details. # # You should", "guid. :param sysvolpath: Path to the sysvol folder :param dnsdomain: DNS name of", "container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\":", "password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm,", "is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\"", "machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a", "the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start()", "%u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\",", "registry database :param session_info: Session information :param credentials: Credentials :param lp: Loadparm context", "% netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)]", "maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN, 1)", "be fixed into the database via the database # modifictions below, but we", "= data.lstrip() if data is None or data == \"\": make_smbconf(smbconf, hostname, domain,", "is None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128,", "os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path,", "samdb: An LDB object on the SAM db :param lp: an LP object", ":param credentials: Credentials :param lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb =", "allocate rids. if next_rid < 1000 or next_rid > 1000000000: error = \"You", "ProvisionResult(object): def __init__(self): self.paths = None self.domaindn = None self.lp = None self.samdb", "the sysvol folder :param dnsdomain: DNS domain name of the AD domain :param", "password between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None:", "domain)) if rootdn is None: rootdn = domaindn if configdn is None: configdn", "ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private dir.", "# we need to freeze the zone while we update the contents if", "\"sid generator = \" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon =", "if hostip is not None: hostip_base_line = \" IN A \" + hostip", "# the Free Software Foundation; either version 3 of the License, or #", "wheel_gid): \"\"\"setup reasonable name mappings for sam names to unix names. :param samdb:", "def create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list file\"\"\" # note that we", "nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start() # only", "nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if hostip6 is not None: hostip6_base_line =", "ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start() # only install", "paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type,", "not None if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() #", "lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list file\"\"\" # note that", "disk secrets_ldb.transaction_commit() # the commit creates the dns.keytab, now chown it dns_keytab_path =", "cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed", "def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None,", "configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\":", "logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid),", "policy GUIDs # Default GUID for default policy are described at # \"How", "one we computed earlier samdb.set_schema(schema) # Set the NTDS settings DN manually -", "logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now commit", "Default GUID for default policy are described at # \"How Core Group Policy", "session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass,", "lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege =", "been found. Using loopback.\") hostip = '127.0.0.1' else: hostip = hostips[0] if len(hostips)", "\"member server\", \"standalone\") if serverrole == \"domain controller\": smbconfsuffix = \"dc\" elif serverrole", "NOT change these default values without discussion with the # team and/or release", ":param policyguid_dc: GUID of the default domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid)", "\"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(),", "subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a file into", "{ \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill ==", "1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid,", "\"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\":", "none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\"))", "else: hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if hostip is", "path: Path to the registry database :param session_info: Session information :param credentials: Credentials", "paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list =", "%s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin", "lockdir_line = \"\" if sid_generator == \"internal\": sid_generator_line = \"\" else: sid_generator_line =", "'%s'! Please remove the %s file and let provision generate it\" % (lp.get(\"workgroup\").upper(),", "realm: Realm name :param domainguid: GUID of the domain. :param ntdsguid: GUID of", "= \"internal\" if backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root or", "Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP", "display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), {", "logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\" %", "not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain = lp.get(\"realm\") if dnsdomain", "shortname ] if secure_channel_type == SEC_CHAN_BDC and dnsname is not None: # we", "impact on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level", "create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now", "ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None,", "Physical path for the netlogon folder :param sysvol: Physical path for the sysvol", "a domain that cannot allocate rids. if next_rid < 1000 or next_rid >", "assert smbconf is not None if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname", "ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen realm '%s'! Please remove the smb.conf", "for name in names: try: return nssfn(name) except KeyError: pass raise KeyError(\"Unable to", "logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"),", "on a domain and forest function level which itself is higher than its", "assert paths.sysvol is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill ==", "= domain names.realm = realm names.netbiosname = netbiosname names.hostname = hostname names.sitename =", "names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid,", "provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel()", "to the sam.ldb :param basedn: A string containing the base DN of the", "not None: hostip_base_line = \" IN A \" + hostip hostip_host_line = hostname", "= None self.domaindn = None self.lp = None self.samdb = None def check_install(lp,", "paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\":", "\"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499), })", "domainsid: The SID of the domain :param dnsdomain: The DNS name of the", "%s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not", "the domain. :param ntdsguid: GUID of the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid,", "\"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\"", "' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, {", "note that we use no variable substitution on this file # the substitution", "session_info: Session information :param credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm", "for the created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab)", "for root, dirs, files in os.walk(sysvol, topdown=False): for name in files: if canchown:", "paths.private_dir = lp.get(\"private dir\") # This is stored without path prefix for the", "to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\",", "if domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression tries", "name in dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn,", "These will be fixed into the database via the database # modifictions below,", "named.conf file. :param dnsdomain: DNS Domain name :param hostname: Local hostname :param realm:", "hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None,", "msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum", "Loadparm context :return: LDB handle for the created secrets database \"\"\" if os.path.exists(paths.secrets):", "\" + hostip hostip_host_line = hostname + \" IN A \" + hostip", "= setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database.", "session_info, provision_backend, lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass,", "elif serverrole == \"standalone\": smbconfsuffix = \"standalone\" if sid_generator is None: sid_generator =", "paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns =", "if targetdir is not None: privatedir_line = \"private dir = \" + os.path.abspath(os.path.join(targetdir,", "newnbname = \"\" for x in netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS:", "> 1: logger.warning(\"More than one IPv4 address found. Using %s.\", hostip) if serverrole", "the registry. :param path: Path to the registry database :param session_info: Session information", "samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid else:", "lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync,", "handle for the created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir,", "ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise", "AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" :", "not specified in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is None:", "+ hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" + hostip6 else: hostip6_base_line =", "serverrole=serverrole, schema=schema) if schema is None: schema = Schema(domainsid, schemadn=names.schemadn) # Load the", ":param domainsid: The SID of the domain :param dnsdomain: The DNS name of", "paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\",", "self.secrets = None self.keytab = None self.dns_keytab = None self.dns = None self.winsdb", "0 is this value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\",", "+ rootdn names.dnsdomain = dnsdomain names.domain = domain names.realm = realm names.netbiosname =", "msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] =", "then populate the database. :note: This will wipe the Sam Database! :note: This", "\" + hostip6 else: hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\"", "setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\":", "nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings for sam names to unix names.", "domain names.realm = realm names.netbiosname = netbiosname names.hostname = hostname names.sitename = sitename", "realm = dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm =' was not", "name in names: try: return nssfn(name) except KeyError: pass raise KeyError(\"Unable to find", "a new, random password between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if", "== \"\": raise ProvisioningError(\"guess_names: 'realm =' was not specified in supplied %s. Please", "= \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn,", "\"CN=Configuration,\" + rootdn if schemadn is None: schemadn = \"CN=Schema,\" + configdn if", "dnsdomain: DNS Domain name :param domaindn: DN of the Domain :param hostip: Local", "newnbname[0:15] else: netbiosname = hostname.upper() if serverrole is None: serverrole = \"standalone\" assert", "= security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "paths.smbconf = lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None,", "if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to", "quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the", "is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is None: adminpass", "backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif", "domaindn: DN of the Domain :param hostip: Local IPv4 IP :param hostip6: Local", "if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind gid %u\" % (", "session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try:", "a ldb in the private dir. :param ldb: LDB object. :param ldif_path: LDIF", "if serverrole is None: serverrole = \"standalone\" assert serverrole in (\"domain controller\", \"member", "self.value = value def __str__(self): return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A", "be that this attribute does not exist in this schema raise if serverrole", "root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in", "None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \" + lp.get(\"realm\"))", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "lp): \"\"\"Setup the registry. :param path: Path to the registry database :param session_info:", "dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is", "raise ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if", "os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)):", "keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\":", "logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the", "# # You should have received a copy of the GNU General Public", "invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1):", "with substitution variables. \"\"\" assert ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path,", "except Exception: secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb to disk secrets_ldb.transaction_commit() #", "GUIDs # Default GUID for default policy are described at # \"How Core", "samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000,", "onto the database. # Various module (the password_hash module in particular) need #", "realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to a secrets database. :param", "\"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" %", "\"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole", "0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind gid", "\\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\", "the lastest USN modified by a provision or an upgradeprovision :param sam: An", "\"\"\" for name in names: try: return nssfn(name) except KeyError: pass raise KeyError(\"Unable", "len(entry): range = [] idx = 0 p = re.compile(r'-') for r in", "None self.hostname = None self.sitename = None self.smbconf = None def update_provision_usn(samdb, low,", "user. :param users_gid: gid of the UNIX users group. :param wheel_gid: gid of", "lp): \"\"\"Setup the secrets database. :note: This function does not handle exceptions and", "\"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by a provision", "else: netbiosname = hostname.upper() if serverrole is None: serverrole = \"standalone\" assert serverrole", "# chmod needed to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError:", "None: netbiosname = hostname # remove forbidden chars newnbname = \"\" for x", "create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill,", "\"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if not os.path.exists(p):", "chown %s to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration", "in (\"domain controller\", \"member server\", \"standalone\") if invocationid is None: invocationid = str(uuid.uuid4())", "return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "pass raise KeyError(\"Unable to find user/group in %r\" % names) findnss_uid = lambda", "'%s'! Please remove the smb.conf file and let provision generate it\" % (lp.get(\"server", "{ \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel()", "password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL)", "set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl, domsid) for root, dirs, files in", "netbios hostname '%s'!\" % (realm, netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names: Realm", "serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm =' was", "secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is", "samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from samba.ms_display_specifiers", "to the highest USN modified by (upgrade)provision, 0 is this value is unknown", ":param high: The highest USN modified by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\"", "# Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema)", "some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname,", "sid: The domain sid. :param domaindn: The domain DN. :param root_uid: uid of", "figure out the weird errors # loading an empty smb.conf gives, then we", "os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir,", "res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn,", "setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if", "hostip is not None: hostip_base_line = \" IN A \" + hostip hostip_host_line", "need to freeze the zone while we update the contents if targetdir is", "dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\"", "% LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" %", "0775) # we need to freeze the zone while we update the contents", "lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp", "def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a file containing zone statements suitable", "( 1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do NOT change these default", "setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp,", "% lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match", "role\") if serverrole is None: raise ProvisioningError(\"guess_names: 'server role' not specified in supplied", ":return: A string with the complete path to the policy folder \"\"\" if", "name :param domainguid: GUID of the domain. :param ntdsguid: GUID of the hosts", "] if secure_channel_type == SEC_CHAN_BDC and dnsname is not None: # we are", "\"internal\" if backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root or \"root\"])", "\"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return", "DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA 4 on", "of AD we are emulating. # These will be fixed into the database", "with substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path,", "class ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm = None self.hkcu = None", "and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid", "\"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception:", "hostip6: Local IPv6 IP :param hostname: Local hostname :param realm: Realm name :param", "string with the complete path to the policy folder \"\"\" if guid[0] !=", "better or worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper() if", "The erase parameter controls whether to erase the existing data, which may not", "not None: # now display slapd_command_file.txt to show how slapd must be #", "the original in EJS: # Copyright (C) <NAME> <<EMAIL>> 2005 # # This", "# This is partially Samba4 specific and should be replaced by the correct", "DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs", "<NAME> <<EMAIL>> 2008-2009 # # Based on the original in EJS: # Copyright", "lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in", "\"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\":", "os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn)", "\\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\", "samba.registry from samba.schema import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\"", "Path to private directory :param keytab_name: File name of DNS keytab file \"\"\"", "% provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), {", "file) # Descriptors of naming contexts and other important objects # \"get_schema_descriptor\" is", "try: os.chown(sysvol, -1, gid) except OSError: canchown = False else: canchown = True", "paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths", "if domain == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to", "new shares config db if there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up", "names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass,", "invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\":", "computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), {", "on the first DC, it should be # replicated with DNS replication create_zone_file(lp,", "Realm '%s' must not be equal to short domain name '%s'!\" % (realm,", "None self.domain = None self.hostname = None self.sitename = None self.smbconf = None", "setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying", "data, which may not be stored locally but in LDAP. \"\"\" assert session_info", "% (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"]", "= \"member\" elif serverrole == \"standalone\": smbconfsuffix = \"standalone\" if sid_generator is None:", "= dom_for_fun_level # Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names,", "res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the", "path for the sysvol folder :param dnsdomain: The DNS name of the domain", "scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res)", "ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN in", "(lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\")", "remove the smb.conf file and let provision generate it\" % (lp.get(\"server role\").upper(), serverrole,", "folder :param dnsdomain: The DNS name of the domain :param domainsid: The SID", "\"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() *", "\"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\":", "\"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update)", "None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir,", "a copy of the GNU General Public License # along with this program.", "domaindn = \"DC=\" + netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() ==", "the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid +", "setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up", ":param ldb: LDB file to import into. :param ldif_path: Path to the LDIF", "logger.warning(\"No external IPv4 address has been found. Using loopback.\") hostip = '127.0.0.1' else:", "a DNS zone file, from the info in the current database. :param paths:", "raise ProvisioningError(\"guess_names: 'server role=%s' in %s must match chosen server role '%s'! Please", "to stop the modules loading - we # just want to wipe and", "afterward by next provision to figure out if the field have been modified", "raise KeyError(\"Unable to find user/group in %r\" % names) findnss_uid = lambda names:", "setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend,", "== realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to hostname '%s'!\"", "and transaction on purpose, it's up to the caller to do this job.", "folder \"\"\" if guid[0] != \"{\": guid = \"{%s}\" % guid policy_path =", "\"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf", "policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon,", "\"You want to run SAMBA 4 with a next_rid of %u, \" %", "self.lp = None self.samdb = None def check_install(lp, session_info, credentials): \"\"\"Check whether the", "private_dir): \"\"\"Write out a file containing zone statements suitable for inclusion in a", "isinstance(invocationid, str) if ntdsguid is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line", "by a provision or an upgradeprovision :param sam: An LDB object pointing to", "serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception:", "it causes problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain))", "names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain = domain names.realm =", "file\"\"\" # note that we use no variable substitution on this file #", "the Sam Database! :note: This function always removes the local SAM LDB file.", "= \"\" lockdir_line = \"\" if sid_generator == \"internal\": sid_generator_line = \"\" else:", "\"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr })", ":param hostname: Local hostname :param realm: Realm name :param domainguid: GUID of the", "AD we are emulating. # These will be fixed into the database via", "\" % (next_rid) error += \"the valid range is %u-%u. The default is", "at a time, # but we don't delete the old record that we", "= os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update =", "%s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon,", "\"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid +", "raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match chosen domain '%s'! Please remove", "samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type is not \"ldb\":", "sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn,", "Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration", "\"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath,", "check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc import security", "an absolute path to the provision tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(),", ": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain,", "for setting up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import b64encode", "the default # this ensures that any smb.conf parameters that were set #", "valid_netbios_name, version, ) from samba.dcerpc import security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA,", "to short host name '%s'!\" % (domain, netbiosname)) else: domain = netbiosname if", "by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message()", "names): \"\"\"Find a user or group from a list of possibilities. :param nssfn:", "}) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return", "folder :param gid: The GID of the \"Domain adminstrators\" group :param domainsid: The", "display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users", "paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This is stored without path", "privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the", "0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO for a domain", "}) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup the", "lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp)", "controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf does not have a [netlogon] share,", "default domain policy :param policyguid_dc: GUID of the default domain controler policy \"\"\"", "in a named.conf file (including GSS-TSIG configuration). :param path: Path of the new", "dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path,", "code to update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def", "before the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) #", "Credentials :param lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info,", "if there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf,", "of USN modified by provision and upgradeprovision. This value is used afterward by", "def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database. :param path: Path to the", "\\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\", "domaindn result.paths = paths result.lp = lp result.samdb = samdb return result def", "specified in supplied %s!\" % lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper() if", "functionality levels onto the database. # Various module (the password_hash module in particular)", "domsid): setntacl(lp, path, acl, domsid) for root, dirs, files in os.walk(path, topdown=False): for", "secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to a", "samba.dcerpc import security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import", "[sysvol] share, but you\" \" are configuring a DC.\") logger.info(\"Please either remove %s", "hostname '%s'!\" % (realm, netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names: Realm '%s'", "ready to use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS", "# This is stored without path prefix for the \"privateKeytab\" attribute in #", "track range of USN modified by provision and upgradeprovision. This value is used", ":param ldif_path: LDIF file path. :param subst_vars: Optional dictionary with substitution variables. \"\"\"", "security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf if there", "dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration", "names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\": # Set up", "and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type = \"ldb\"", "It might be that this attribute does not exist in this schema raise", "\"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names,", "sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname,", "samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import (", "actual DC function level (2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality =", "appended (default) \"\"\" tab = [] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" %", "= None self.keytab = None self.dns_keytab = None self.dns = None self.winsdb =", "lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen realm '%s'!", "= os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt =", "el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s' %", "policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID based SPNs", "else: return None class ProvisionResult(object): def __init__(self): self.paths = None self.domaindn = None", "None self.dns = None self.winsdb = None self.private_dir = None class ProvisionNames(object): def", "keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\":", "use no variable substitution on this file # the substitution is done at", "credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account found\") def findnss(nssfn,", "dirs: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) #", "pass for el in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn)", "# Set the SYSVOL_ACL on the sysvol folder and subfolder (first level) setntacl(lp,sysvol,", "= [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] =", "up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb =", "session_info, credentials): \"\"\"Check whether the current install seems ok. :param lp: Loadparm context", "names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner", "\"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "dnsdomain is None or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not specified in", "wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"])", "secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]]", "if sitename is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn names.domaindn =", "\\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl,", "\"the valid range is %u-%u. The default is %u.\" % ( 1000, 1000000000,", "subst_vars: Optional variables to subsitute in LDIF. :param nocontrols: Optional list of controls,", "under the terms of the GNU General Public License as published by #", "read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc import security from samba.dcerpc.misc import", "paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update", "serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database. :note: This will", "configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if hostname is None:", "A string containing the base DN of the provision (ie. DC=foo, DC=bar) :return:", "str(names.rootdn)) if lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0,", "see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\"", "hostip: Local IPv4 IP :param hostip6: Local IPv6 IP :param hostname: Local hostname", "Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid", "manager. They have a big impact on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2", "already around # before the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\"", "= hostname + \" IN AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN", "\"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "\"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\":", "\"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for", "\"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info,", "configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return", "on the provision/join command line are set in the resulting smb.conf f =", "= Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator", "schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel))", "= DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA 4", "= findnss_gid([users or \"users\", 'users', 'other', 'staff']) if wheel is None: wheel_gid =", "not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid,", "= policyguid_dc.upper() if adminpass is None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass is", "am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD schema\") # Load the schema from", ":param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\":", "os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown", "at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are installed, your Samba4", "0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos", "% (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname = netbiosname.lower() # We don't", "4 with a next_rid of %u, \" % (next_rid) error += \"the valid", "OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind gid %u\" %", "from the one we computed earlier samdb.set_schema(schema) # Set the NTDS settings DN", "useeadb, lp=lp) if lp is None: lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp,", "except ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that", "\"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl, domsid) for root, dirs,", "domaindn: The domain DN. :param root_uid: uid of the UNIX root user. :param", "to use.\"\"\" if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\")", "# Make a new, random password between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128,", "high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE)", "The GID of the \"Domain adminstrators\" group :param domainsid: The SID of the", "== FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type is not \"ldb\": if", "raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain = lp.get(\"realm\") if dnsdomain is None", "if domaindn is None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain ==", "return range else: return None class ProvisionResult(object): def __init__(self): self.paths = None self.domaindn", "== \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type", "host name '%s'!\" % (domain, netbiosname)) else: domain = netbiosname if domaindn is", "dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig)", "% ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets", "%s for an example configuration include file for BIND\", paths.namedconf) logger.info(\"and %s for", "% names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup", "path of policy given its guid. :param sysvolpath: Path to the sysvol folder", "to be <16 netbiosname = newnbname[0:15] else: netbiosname = hostname.upper() if serverrole is", "up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb,", "sitename is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn", "\"\"\" if guid[0] != \"{\": guid = \"{%s}\" % guid policy_path = os.path.join(sysvolpath,", "acl, domsid) for root, dirs, files in os.walk(path, topdown=False): for name in files:", "\"\"\"Setup a ldb in the private dir. :param ldb: LDB file to import", "\"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\"", "None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), {", "hostip is None: logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp, False) if len(hostips)", "str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding", "ACL on the sysvol/<dnsname>/Policies folder and the policy folders beneath. :param sysvol: Physical", "anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] =", "if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default", "isinstance(domainguid, str) # Only make a zone file on the first DC, it", "\\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def", "License as published by # the Free Software Foundation; either version 3 of", ":param dnsdomain: DNS Domain name :param domaindn: DN of the Domain :param hostip:", "of the AD domain :param policyguid: GUID of the default domain policy :param", "samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) #", "% serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain:", "domain sid. :param domaindn: The domain DN. :param root_uid: uid of the UNIX", "= DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc", "if backend_type is None: backend_type = \"ldb\" sid_generator = \"internal\" if backend_type ==", "and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb,", "entries to point at the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\":", "\"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or", "object. :param idmap: IDmap db object. :param sid: The domain sid. :param domaindn:", "specified name was not a valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__(", "value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if", "to point at the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn,", "None self.hkpt = None self.samdb = None self.idmapdb = None self.secrets = None", "eadb and not lp.get(\"posix:eadb\"): if targetdir is not None: privdir = os.path.join(targetdir, \"private\")", "not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf if there isn't one", "names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return names", "if rootdn is None: rootdn = domaindn if configdn is None: configdn =", "up group policies (domain policy and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid,", "version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc,", "SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid,", "\"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "%u\" % ( dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc + \" unfreeze", "zone file, from the info in the current database. :param paths: paths object", "name of the AD domain :param guid: The GUID of the policy :return:", "# than one record for this SID, realm or netbios domain at a", "information :param credentials: Credentials :param lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb", "class ProvisionResult(object): def __init__(self): self.paths = None self.domaindn = None self.lp = None", "\"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif =", "container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), {", "\"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec =", "1000 or next_rid > 1000000000: error = \"You want to run SAMBA 4", "2008-2009 # # Based on the original in EJS: # Copyright (C) <NAME>", "path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path,", "if provision_backend.slapd_command_escaped is not None: # now display slapd_command_file.txt to show how slapd", "the SAM database. Alternatively, provision() may call this, and then populate the database.", "db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid,", "logger.info(\"See %s for an example configuration include file for BIND\", paths.namedconf) logger.info(\"and %s", "b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb,", "+ \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema, serverrole,", "realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example", "we don't have more # than one record for this SID, realm or", "os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, {", "'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p =", "= spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS", ":param netlogon: Physical path for the netlogon folder :param sysvol: Physical path for", "file (including GSS-TSIG configuration). :param paths: all paths :param realm: Realm name :param", "provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb to", "session_info, backend_credentials, lp): \"\"\"Setup the secrets database. :note: This function does not handle", "Set acls on Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb,", "with DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid,", "import samba from samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var,", "%s\", paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig,", "LDAP backend\" if provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri", "\"\"\" # Provision does not make much sense values larger than 1000000000 #", "if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema", "around # before the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" %", "dnsdomain names.domain = domain names.realm = realm names.netbiosname = netbiosname names.hostname = hostname", "[machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not", "domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL for the sysvol share and the", "os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\":", "must be # started next time logger.info(\"Use later the following commandline to start", "found. Using loopback.\") hostip = '127.0.0.1' else: hostip = hostips[0] if len(hostips) >", "controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private dir. :param", "policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is None:", "(lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain controller\": if domain is None:", "will be ready to use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\" %", "up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb,", "return nssfn(name) except KeyError: pass raise KeyError(\"Unable to find user/group in %r\" %", "couple of basic settings. \"\"\" assert smbconf is not None if hostname is", "\"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\")", "paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write", "assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to point at the newly created", "BIND\", paths.namedconf) logger.info(\"and %s for further documentation required for secure DNS \" \"updates\",", "SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not None: try: os.chown(dns_dir,", "lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param", "the NTDS settings DN manually - in order to have it already around", "must not be equal to short host name '%s'!\" % (domain, netbiosname)) else:", "names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid,", "started next time logger.info(\"Use later the following commandline to start slapd, then Samba:\")", "let provision generate it\" % lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s'", "modified by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low, high)) delta =", "smb.conf does not have a [netlogon] share, but you are configuring a DC.\")", "ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole })", "by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir):", "\"\"\"Add DNS specific bits to a secrets database. :param secretsdb: Ldb Handle to", "= \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and settings\")", "account found\") def findnss(nssfn, names): \"\"\"Find a user or group from a list", "ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param", "= ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def", "__init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is not a valid NetBIOS name\"", "is None: # This will, for better or worse, default to 'WORKGROUP' domain", "dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path,", "# Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 #", "sam.ldb :return: an integer corresponding to the highest USN modified by (upgrade)provision, 0", "smb.conf file based on a couple of basic settings. \"\"\" assert smbconf is", "else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\"", "setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole,", ":param path: Path of the new named.conf file. :param dnsdomain: DNS Domain name", "\"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\"", "provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap", "# impersonate domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not", "(2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes", "is None: domaindn = \"DC=\" + netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if", "realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs,", "show how slapd must be # started next time logger.info(\"Use later the following", "= ProvisionResult() result.domaindn = domaindn result.paths = paths result.lp = lp result.samdb =", "lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the", "without path prefix for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\"", "database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir,", "options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\" if provision_backend.type is not \"ldb\": ldap_backend_line", "ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid):", "[res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE)", "rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None,", "def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for provisioning.", "= samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"):", "res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin configuration file. :param path:", "\"\"\"Write out a file containing zone statements suitable for inclusion in a named.conf", "# quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading", "\"\" gc_msdcs_ip6_line = \"\" if hostip is not None: hostip_base_line = \" IN", "Software Foundation; either version 3 of the License, or # (at your option)", "line are set in the resulting smb.conf f = open(smbconf, mode='w') lp.dump(f, False)", "os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775) # we need to", "<NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # # Based on", "paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or", "LP object \"\"\" # Set ACL for GPO root folder root_policy_path = os.path.join(sysvol,", "PURPOSE. See the # GNU General Public License for more details. # #", "domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None,", "samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate domain admin admin_session_info = admin_session(lp,", "# create/adapt the group policy GUIDs # Default GUID for default policy are", "== \"domain controller\": smbconfsuffix = \"dc\" elif serverrole == \"member server\": smbconfsuffix =", "setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out", "\" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" + hostip6 else: hostip6_base_line", "Local IPv6 IP :param hostname: Local hostname :param realm: Realm name :param domainguid:", "be replaced by the correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\":", "and AD schema\") # Load the schema from the one we computed earlier", "while we update the contents if targetdir is None: rndc = ' '.join(lp.get(\"rndc", "for name in files: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name),", "time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line,", "lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain", "tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id", "except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False,", "names to unix names. :param samdb: SamDB object. :param idmap: IDmap db object.", "\" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\")", "ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE:", "paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to cope with umask os.chmod(dns_dir, 0775)", "file, from the info in the current database. :param paths: paths object :param", "wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb,", "sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain,", "version, ) from samba.dcerpc import security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, )", "logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\":", "server\", \"standalone\") if serverrole == \"domain controller\": smbconfsuffix = \"dc\" elif serverrole ==", "folder and the policy folders beneath. :param sysvol: Physical path for the sysvol", "= domaindn names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn", "dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and the", ":param sid: The domain sid. :param domaindn: The domain DN. :param root_uid: uid", "descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The", "% ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path", "paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path =", "delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\"", "be determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\",", "ldapi_uri): \"\"\"Create a PHP LDAP admin configuration file. :param path: Path to write", "names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\")", "realm, dnsdomain, private_dir): \"\"\"Write out a file containing zone statements suitable for inclusion", "provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain,", "IN A \" + hostip gc_msdcs_ip_line = \"gc._msdcs IN A \" + hostip", "constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"),", "EJS: # Copyright (C) <NAME> <<EMAIL>> 2005 # # This program is free", "we are about to modify, # because that would delete the keytab and", "class InvalidNetbiosName(Exception): \"\"\"A specified name was not a valid NetBIOS name.\"\"\" def __init__(self,", "controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path,", "\"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the", "newnbname = \"%s%c\" % (newnbname, x) # force the length to be <16", "data! \"\"\" if domainsid is None: domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid)", "realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to hostname '%s'!\" %", "is not None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain", "# before the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn)", "if paths.bind_gid is not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) #", "setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set", "realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf file based on", "def set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN in sam.ldb This field is", "it already around # before the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS", "!= 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s' % shortname", "def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\", ":param session_info: Session information :param credentials: Credentials :param lp: Loadparm context \"\"\" if", "samdb: An LDB object connect to sam.ldb :param low: The lowest USN modified", "to use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain:", "paths.bind_gid) # chmod needed to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except", "delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta)", "def setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param path: Path to the registry", "\"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was not a valid", "base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high))", "if serverrole is None: serverrole = lp.get(\"server role\") if serverrole is None: raise", "# DB samdb.connect(path) if fill == FILL_DRS: return samdb samdb.transaction_start() try: # Set", "the following commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also", "os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb =", "the schema from the one we computed earlier samdb.set_schema(schema) # Set the NTDS", "will be added or none (using transactions). :param ldb: LDB file to import", "install a new shares config db if there is none if not os.path.exists(paths.shareconf):", "= samba.generate_random_password(128, 255) if machinepass is None: machinepass = samba.generate_random_password(128, 255) if dnspass", "Optional list of controls, can be None for no controls \"\"\" assert isinstance(ldif_path,", "= [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try:", "PHP LDAP admin configuration file. :param path: Path to write the configuration to.", "\"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname,", "folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger, session_info,", "sid_generator, useeadb, lp=lp) if lp is None: lp = samba.param.LoadParm() lp.load(smbconf) names =", "might be determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb,", "\"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn)) if lastProvisionUSNs is not", "\"\"\" assert smbconf is not None if hostname is None: hostname = socket.gethostname().split(\".\")[0]", "findnss_gid([users or \"users\", 'users', 'other', 'staff']) if wheel is None: wheel_gid = findnss_gid([\"wheel\",", "32) if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass is None:", ") from samba.dcerpc import security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from", "make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp is None:", "isn't one there already if os.path.exists(smbconf): # if Samba Team members can't figure", "x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #force the", "connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now we can connect to the", "if fill == FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), {", "generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names:", "\"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info,", "domain. :param ntdsguid: GUID of the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str)", "domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None,", "chosen server role '%s'! Please remove the smb.conf file and let provision generate", "setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files in os.walk(sysvol, topdown=False): for name in", "Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, ) from samba.dcerpc import", "\"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid)", "create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO for a domain :param sysvolpath:", "to track range of USN modified by provision and upgradeprovision. This value is", "not have a [sysvol] share, but you\" \" are configuring a DC.\") logger.info(\"Please", "domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None,", ":param paths: all paths :param realm: Realm name :param dnsdomain: DNS Domain name", "the resulting smb.conf f = open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap,", "os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in dirs:", "= guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths =", "then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result =", "paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or", "None self.hku = None self.hkpd = None self.hkpt = None self.samdb = None", "( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif", "statements suitable for inclusion in a named.conf file (including GSS-TSIG configuration). :param paths:", "database file! \"\"\" # Provision does not make much sense values larger than", "DN of the Domain :param hostip: Local IPv4 IP :param hostip6: Local IPv6", "right msDS-SupportedEncryptionTypes into the DB # In future, this might be determined from", "dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775) # we", "time logger.info(\"Use later the following commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This", "None realm = realm.upper() if lp is None: lp = samba.param.LoadParm() #Load non-existant", "str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), {", "if targetdir is None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze", "ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm = None self.hkcu =", "short host name '%s'!\" % (domain, netbiosname)) else: domain = netbiosname if domaindn", "msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\",", "else: canchown = True # Set the SYSVOL_ACL on the sysvol folder and", "ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that", "highest USN modified by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low, high))", "connect to the DB - the schema won't be loaded from the #", "idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup", "no controls \"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def", "hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri):", "its own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is not None: ntdsguid_line =", "next_rid of %u, \" % (next_rid) error += \"the valid range is %u-%u.", "+ os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\",", "lockdir_line = \"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line", "\\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\", "value def __str__(self): return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified name", "create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin configuration file. :param path: Path to", "None: rootdn = domaindn if configdn is None: configdn = \"CN=Configuration,\" + rootdn", "serverrole in (\"domain controller\", \"member server\", \"standalone\") if serverrole == \"domain controller\": smbconfsuffix", "LDAP. \"\"\" assert session_info is not None # We use options=[\"modules:\"] to stop", "hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend", "ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type", "\"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This is stored without", "except KeyError: pass raise KeyError(\"Unable to find user/group in %r\" % names) findnss_uid", ":param path: Path to the privileges database. :param session_info: Session info. :param credentials:", "InvalidNetbiosName(Exception): \"\"\"A specified name was not a valid NetBIOS name.\"\"\" def __init__(self, name):", "domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\"", "SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap", "short domain name '%s'!\" % (realm, domain)) if rootdn is None: rootdn =", "up to the caller to do this job. :param path: Path to the", "== \"domain controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf does not have a", "None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new", "if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm =' was not specified in supplied", "= \"\" if sid_generator == \"internal\": sid_generator_line = \"\" else: sid_generator_line = \"sid", "order to have it already around # before the provisioned tree exists and", "LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry from samba.schema import Schema from samba.samdb", "paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or", "% names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception:", "+ lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list file\"\"\" # note", "don's load the global schema and don't connect # quite yet samdb =", "str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl", "os.walk(path, topdown=False): for name in files: setntacl(lp, os.path.join(root, name), acl, domsid) for name", "commit the secrets.ldb to disk secrets_ldb.transaction_commit() # the commit creates the dns.keytab, now", "\"standalone\") if serverrole == \"domain controller\": smbconfsuffix = \"dc\" elif serverrole == \"member", "pointing to the sam.ldb :param basedn: A string containing the base DN of", "logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise", "policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp)", "rdn_name will handle # it, and it causes problems for modifies anyway msg", "\"member\" elif serverrole == \"standalone\": smbconfsuffix = \"standalone\" if sid_generator is None: sid_generator", "\"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)]", "None domain = domain.upper() assert realm is not None realm = realm.upper() if", "This will, for better or worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain", "\"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl =", "the sysvol folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs,", "partitions for the SAM database. Alternatively, provision() may call this, and then populate", "rootdn names.dnsdomain = dnsdomain names.domain = domain names.realm = realm names.netbiosname = netbiosname", "low, high, replace=False): \"\"\"Update the field provisionUSN in sam.ldb This field is used", "\"users\", 'users', 'other', 'staff']) if wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else:", "# Now set up the right msDS-SupportedEncryptionTypes into the DB # In future,", "and upgradeprovision. This value is used afterward by next provision to figure out", "policy are described at # \"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if", "result.lp = lp result.samdb = samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None,", "Based on the original in EJS: # Copyright (C) <NAME> <<EMAIL>> 2005 #", "This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes the", "descr, }) # The LDIF here was created when the Schema object was", "name :param domaindn: DN of the Domain :param hostip: Local IPv4 IP :param", "any later version. # # This program is distributed in the hope that", "the provision/join command line are set in the resulting smb.conf f = open(smbconf,", "A LDB object pointing to the sam.ldb :param basedn: A string containing the", "controls \"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb,", "\"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up", "The default is %u.\" % ( 1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION:", "ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE)", "None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names:", "Copyright (C) <NAME> <<EMAIL>> 2008-2009 # # Based on the original in EJS:", "os.mkdir(dns_dir, 0775) # we need to freeze the zone while we update the", "'server role' not specified in supplied %s!\" % lp.configfile) serverrole = serverrole.lower() realm", "None: serverrole = \"standalone\" assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if", "{ \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname,", "to netbios hostname '%s'!\" % (realm, netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names:", "msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid", "slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result", "realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname,", "None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass is None: # Make a new,", "raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be", "name was not a valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The", "[\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"] =", "next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None,", "dnsdomain, guid): \"\"\"Return the physical path of policy given its guid. :param sysvolpath:", "realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the right msDS-SupportedEncryptionTypes", "not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\"", "DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise", "the default domain policy :param policyguid_dc: GUID of the default domain controler policy", "not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression tries to ensure that", "samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate", "role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain controller\": if domain is None: #", "[ndr_pack(domainsid)] # This complex expression tries to ensure that we don't have more", "setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\":", "names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\"", "stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn result.paths = paths", "samdb: A LDB object pointing to the sam.ldb :param basedn: A string containing", "an example configuration include file for BIND\", paths.namedconf) logger.info(\"and %s for further documentation", "nssfn: NSS Function to try (should raise KeyError if not found) :param names:", "commit creates the dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path)", "we are a domain controller then we add servicePrincipalName # entries for the", "\\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return", "is this value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE,", "ldif_path, subst_vars): \"\"\"Import a LDIF a file into a LDB handle, optionally substituting", "admin_session import samba from samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file,", "DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\"", "lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None,", "found. Using %s.\", hostip) if serverrole is None: serverrole = lp.get(\"server role\") assert", "file on the first DC, it should be # replicated with DNS replication", "\"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt'))", "chosen realm '%s'! Please remove the smb.conf file and let provision generate it\"", "the NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn,", "\"\"\"Check whether the current install seems ok. :param lp: Loadparm context :param session_info:", "if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info,", "None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a file", "def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder", "if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match chosen", "msg.dn) else: spn = [ 'HOST/%s' % shortname ] if secure_channel_type == SEC_CHAN_BDC", "next provision to figure out if the field have been modified since last", "machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the right msDS-SupportedEncryptionTypes into the DB #", "field have been modified since last provision. :param samdb: An LDB object connect", "names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else:", "\"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up sam.ldb users and", "else: dnsname = None shortname = netbiosname.lower() # We don't need to set", "flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It", "str) if ntdsguid is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line =", "list of possibilities. :param nssfn: NSS Function to try (should raise KeyError if", "you\" \" are configuring a DC.\") logger.info(\"Please either remove %s or see the", "\"\"\" if domainsid is None: domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid) #", "paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\"", "are a domain controller then we add servicePrincipalName # entries for the keytab", "ldap_backend_line = \"# No LDAP backend\" if provision_backend.type is not \"ldb\": ldap_backend_line =", "and/or modify # it under the terms of the GNU General Public License", "= [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in msg: if el != 'dn':", "+= \"the valid range is %u-%u. The default is %u.\" % ( 1000,", "os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names):", "Do NOT change these default values without discussion with the # team and/or", "os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a", "try: os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line =", "realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only", "SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD", "ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm = None self.hkcu = None self.hkcr", "msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in msg: if el !=", "+ \" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out a", "'%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical", "policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid)", "just want to wipe and re-initialise the database, not start it up try:", "else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn,", "be smarter. # Pretend it just didn't exist --abartlet data = open(smbconf, 'r').read()", "= ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"]", "# add the NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid", "here was created when the Schema object was constructed logger.info(\"Setting up sam.ldb schema\")", "= netbiosname names.hostname = hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % (", "0775) p = os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain,", "get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "\"\"\"Write out a DNS zone file, from the info in the current database.", "subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default", "if domainguid is not None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid else: domainguid_line", "privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param path: Path to", "the DB # In future, this might be determined from some configuration kerberos_enctypes", "we use no variable substitution on this file # the substitution is done", "% (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab,", "\"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\":", "controller\": smbconfsuffix = \"dc\" elif serverrole == \"member server\": smbconfsuffix = \"member\" elif", "= lp.get(\"netbios name\") if netbiosname is None: netbiosname = hostname # remove forbidden", "range of the rIDAvailablePool is 1073741823 and # we don't want to create", "path prefix for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab", "in res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"]", "\"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\":", "= None self.winsdb = None self.private_dir = None class ProvisionNames(object): def __init__(self): self.rootdn", "we don't want to create a domain that cannot allocate rids. if next_rid", "database. :param secretsdb: Ldb Handle to the secrets database :param machinepass: Machine password", "lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm =' was not specified in supplied %s.", "\\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\", "\"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec =", "keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a file", "lp=None): \"\"\"Create a new smb.conf file based on a couple of basic settings.", "update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field provisionUSN in sam.ldb This field is", "(realm, netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be", "secrets database. :param session_info: Session info. :param credentials: Credentials :param lp: Loadparm context", "\"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb,", "dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update", "# if Samba Team members can't figure out the weird errors # loading", "Sam Database! :note: This function always removes the local SAM LDB file. The", "{ \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" :", "absolute path to the provision tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file)", "users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), {", "# started next time logger.info(\"Use later the following commandline to start slapd, then", "setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\":", "for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)]", "serverrole, erase=False): \"\"\"Setup the partitions for the SAM database. Alternatively, provision() may call", ":param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\":", "domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match", "1 return range else: return None class ProvisionResult(object): def __init__(self): self.paths = None", "idx = 0 p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r))", "FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode,", "is not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed", "if dnsname is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm]", "fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole", "IN A \" + hostip hostip_host_line = hostname + \" IN A \"", "= \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl, domsid) for root,", "[netlogon] share, but you are configuring a DC.\") logger.info(\"Please either remove %s or", "netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to netbios", "need to set msg[\"flatname\"] here, because rdn_name will handle # it, and it", "\\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return", "lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass,", "path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic", "USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"]", "Public License as published by # the Free Software Foundation; either version 3", "%s\" % str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if", "self.hkcr = None self.hku = None self.hkpd = None self.hkpt = None self.samdb", "\" IN A \" + hostip hostip_host_line = hostname + \" IN A", "paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def", "An LDB object pointing to the sam.ldb :return: an integer corresponding to the", "hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None,", "upgradeprovision. This value is used afterward by next provision to figure out if", "root_uid: uid of the UNIX root user. :param nobody_uid: uid of the UNIX", "\"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp):", "setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param path: Path to the registry database", "= socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden chars newnbname = \"\" for", "Samba4 server # Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>>", "str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement(", "A string with the complete path to the policy folder \"\"\" if guid[0]", "setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings for", "= \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\":", "is used afterward by next provision to figure out if the field have", "idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\": #", "but in LDAP. \"\"\" assert session_info is not None # We use options=[\"modules:\"]", "if (backend_credentials is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb,", "(C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # # Based", "b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup", "lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn,", "\\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "\"\"\"Functions for setting up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import", "is None: dnsdomain = lp.get(\"realm\") if dnsdomain is None or dnsdomain == \"\":", "= serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm ='", ":param gid: The GID of the \"Domain adminstrators\" group :param domainsid: The SID", "dnsname is not None: # we are a domain controller then we add", "samba4 :note: caution, this wipes all existing data! \"\"\" if domainsid is None:", "not None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname,", "Path of the new named.conf file. :param realm: Realm name :param dnsdomain: DNS", "acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp,", "str(domainsid)) for name in dirs: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root,", "this file # the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list,", "# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "\"\" else: sid_generator_line = \"sid generator = \" + sid_generator sysvol = os.path.join(lp.get(\"lock", "provision tempate file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming", "serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip is None:", "= None if targetdir is not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif", "domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole,", "users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None,", "module (the password_hash module in particular) need # to know what level of", "[res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except", "Pretend it just didn't exist --abartlet data = open(smbconf, 'r').read() data = data.lstrip()", "None self.samdb = None self.idmapdb = None self.secrets = None self.keytab = None", "Samba 4 and AD schema\") # Load the schema from the one we", "dnspass = samba.generate_random_password(128, 255) if ldapadminpass is None: # Make a new, random", "configuring a DC.\") logger.info(\"Please either remove %s or see the template at %s\"", "is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp)", "policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger, session_info, credentials, smbconf=None,", "None self.secrets = None self.keytab = None self.dns_keytab = None self.dns = None", "serverrole == \"domain controller\": smbconfsuffix = \"dc\" elif serverrole == \"member server\": smbconfsuffix", ":param dnsdomain: DNS Domain name \"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\")", "ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version", "lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path,", "UNIX users group. :param wheel_gid: gid of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\",", "setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting", "or netbios domain at a time, # but we don't delete the old", "os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb", "targetdir is None: os.system(rndc + \" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger,", "hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line,", "hostip hostip_host_line = hostname + \" IN A \" + hostip gc_msdcs_ip_line =", "the sam.ldb :param basedn: A string containing the base DN of the provision", "[\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if", "configuration include file for BIND\", paths.namedconf) logger.info(\"and %s for further documentation required for", "variables to subsitute in LDIF. :param nocontrols: Optional list of controls, can be", "'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s' % shortname ]", "\"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object):", "wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema", "lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s must match chosen", "os.walk(sysvol, topdown=False): for name in files: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp,", "forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate domain", "file. :param subst_vars: Dictionary with substitution variables. \"\"\" assert ldb is not None", "= None class ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn = None self.configdn", "lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf,", "def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin configuration file. :param path: Path", "= dnsdomain names.domain = domain names.realm = realm names.netbiosname = netbiosname names.hostname =", "targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt,", "setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks", "import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from samba.ms_display_specifiers import", "}) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets database. :note: This function", "machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn", "serverrole is None: serverrole = lp.get(\"server role\") assert serverrole in (\"domain controller\", \"member", "% (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line,", "setup_path(file): \"\"\"Return an absolute path to the provision tempate file specified by file\"\"\"", "release manager. They have a big impact on the whole program! domainControllerFunctionality =", "setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb,", "= str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url", "2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME> <<EMAIL>> 2008-2009", "if dnsdomain is None: dnsdomain = lp.get(\"realm\") if dnsdomain is None or dnsdomain", "# This will, for better or worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\")", "lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase()", "equal to short host name '%s'!\" % (domain, netbiosname)) else: domain = netbiosname", "not exist in this schema raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names,", "# modifictions below, but we need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality)", "database. # Various module (the password_hash module in particular) need # to know", "and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files in os.walk(sysvol,", "\"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note", "\"\"\"Provision samba4 :note: caution, this wipes all existing data! \"\"\" if domainsid is", "SAM db :param netlogon: Physical path for the netlogon folder :param sysvol: Physical", "\" are configuring a DC.\") logger.info(\"Please either remove %s or see the template", "( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets database.", "# You should have received a copy of the GNU General Public License", "debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS,", "\"smb.conf\") elif smbconf is None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) #", "controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by", "setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy", "<<EMAIL>> 2008-2009 # # Based on the original in EJS: # Copyright (C)", "hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"),", "str) # Only make a zone file on the first DC, it should", "None: schemadn = \"CN=Schema,\" + configdn if sitename is None: sitename=DEFAULTSITE names =", "Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped", "configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are installed,", "root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names,", "Domain name :param private_dir: Path to private directory :param keytab_name: File name of", "if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind gid %u\", dns_keytab_path, paths.bind_gid)", "%s\" % adminpass) if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None:", "secrets database. :note: This function does not handle exceptions and transaction on purpose,", "+ 100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499), }) # This is partially", "secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific", "delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low,", "\"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not None: if dnsdomain is None: dnsdomain", "the field provisionUSN in sam.ldb This field is used to track range of", "the domain :param domainsid: The SID of the domain :param domaindn: The DN", "from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN:", "!= realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen realm '%s'! Please", "context :param session_info: Session information :param credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\":", "Using %s.\", hostip) if serverrole is None: serverrole = lp.get(\"server role\") assert serverrole", "import system_session, admin_session import samba from samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir,", "in this schema raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm,", "objects # \"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\", "sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\", "serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\": if paths.netlogon is None:", "# (at your option) any later version. # # This program is distributed", "if len(entry): range = [] idx = 0 p = re.compile(r'-') for r", ":param lp: Loadparm context. :param dnsdomain: DNS Domain name \"\"\" paths = ProvisionPaths()", "ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision", "dir. :param ldb: LDB file to import data into :param ldif_path: Path of", "role\") assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if invocationid is None:", "ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for", "DNS Domain name :param hostname: Local hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"),", "provisioning a Samba4 server # Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C)", "hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal", "= sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx", "any values that are the default # this ensures that any smb.conf parameters", "= \"%s%c\" % (newnbname, x) # force the length to be <16 netbiosname", "# It might be that this attribute does not exist in this schema", "privatedir_line = \"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir", "the group policy GUIDs # Default GUID for default policy are described at", "private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration include", "provisioning. :param lp: Loadparm context. :param dnsdomain: DNS Domain name \"\"\" paths =", "gc_msdcs_ip_line = \"gc._msdcs IN A \" + hostip else: hostip_base_line = \"\" hostip_host_line", "os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except", "new, random password between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type", "None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname is None: netbiosname", "== \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn,", "\"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\"", "the SAM db :param netlogon: Physical path for the netlogon folder :param sysvol:", "re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx", "its actual DC function level (2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality", "base64 import b64encode import os import re import pwd import grp import logging", "else: privatedir_line = \"\" lockdir_line = \"\" if sid_generator == \"internal\": sid_generator_line =", "invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database.", "Path to the secrets database. :param session_info: Session info. :param credentials: Credentials :param", "idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings for sam", "SAM LDB file. The erase parameter controls whether to erase the existing data,", "ntdsguid is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb,", "\"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID based SPNs ntds_dn", "policies (domain policy and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb,", "freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm,", "generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None: domaindn = \"DC=\"", "zone file on the first DC, it should be # replicated with DNS", "useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this wipes all existing data! \"\"\"", "is %u.\" % ( 1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do NOT", "create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path,", "realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp is None: lp = samba.param.LoadParm()", "samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if", "provision_backend.slapd_command_escaped is not None: # now display slapd_command_file.txt to show how slapd must", "gid) except OSError: canchown = False else: canchown = True # Set the", "with the complete path to the policy folder \"\"\" if guid[0] != \"{\":", "is None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is None: policyguid_dc", "sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf = None", "The DN of the domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except", "= b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF", "IN AAAA \" + hostip6 hostip6_host_line = hostname + \" IN AAAA \"", "\"{\": guid = \"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return", "raise # Now commit the secrets.ldb to disk secrets_ldb.transaction_commit() # the commit creates", "= \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path to the provision tempate file", "out the weird errors # loading an empty smb.conf gives, then we need", "b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def", "Samba Team members can't figure out the weird errors # loading an empty", "is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn names.configdn", "given its guid. :param sysvolpath: Path to the sysvol folder :param dnsdomain: DNS", "= findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users', 'other', 'staff']) if", "= provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip is None: logger.info(\"Looking up IPv4", "paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf", ":param policyguid: GUID of the default domain policy :param policyguid_dc: GUID of the", "realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to netbios hostname '%s'!\"", "should be replaced by the correct # DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), {", ":param lp: an LP object \"\"\" # Set ACL for GPO root folder", "True) except OSError: pass os.mkdir(dns_dir, 0775) # we need to freeze the zone", "dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not be", "for more details. # # You should have received a copy of the", "logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def", "LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx = 0 p", "{ \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname,", "str(next_rid + 100 + 499), }) # This is partially Samba4 specific and", "or # (at your option) any later version. # # This program is", "and forest function level which itself is higher than its actual DC function", "names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2]", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s must match chosen server", "hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return", "scope=ldb.SCOPE_ONELEVEL) for policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain,", "session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse.", "Optional variables to subsitute in LDIF. :param nocontrols: Optional list of controls, can", "hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None,", "integer corresponding to the highest USN modified by (upgrade)provision, 0 is this value", "secrets database. :param secretsdb: Ldb Handle to the secrets database :param machinepass: Machine", "name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is not a valid NetBIOS name\" %", "Set the domain functionality levels onto the database. # Various module (the password_hash", "%u-%u. The default is %u.\" % ( 1000, 1000000000, 1000) raise ProvisioningError(error) #", "subsitute in LDIF. :param nocontrols: Optional list of controls, can be None for", "Kerberos configuration suitable for Samba 4 has been \" \"generated at %s\", paths.krb5conf)", "\"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl, domsid)", "IN AAAA \" + hostip6 else: hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line", "msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"]", "\"\"\"Setup the secrets database. :note: This function does not handle exceptions and transaction", "None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to run", "phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are", "setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"),", "via the database # modifictions below, but we need them set from the", "field provisionUSN in sam.ldb This field is used to track range of USN", "lp is None: lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm,", "netbiosname names.hostname = hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname,", "DC=...) :param samdb: An LDB object on the SAM db :param lp: an", "= substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\":", "logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate domain admin admin_session_info = admin_session(lp, str(domainsid))", "samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb", "\"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain),", "Path to the privileges database. :param session_info: Session info. :param credentials: Credentials :param", "= getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names,", "Physical path for the sysvol folder :param dnsdomain: DNS domain name of the", "to ensure that we don't have more # than one record for this", "\\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\", "\"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn,", "lp=lp) logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM", "This program is distributed in the hope that it will be useful, #", "server will be ready to use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\"", "def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a file containing zone statements suitable", "domainsid = security.dom_sid(domainsid) # create/adapt the group policy GUIDs # Default GUID for", "ntdsguid): \"\"\"Write out a DNS zone file, from the info in the current", "set msg[\"flatname\"] here, because rdn_name will handle # it, and it causes problems", "\"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a", "forbidden chars newnbname = \"\" for x in netbiosname: if x.isalnum() or x", "\"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf lp.load(smbconf) # and dump it without", "and the subfolders :param samdb: An LDB object on the SAM db :param", "share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info,", "os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\":", "is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] =", "and it causes problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" %", "name of the AD domain :param policyguid: GUID of the default domain policy", "handle for the created secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path,", "str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif(", "configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None,", "smbconfsuffix = \"dc\" elif serverrole == \"member server\": smbconfsuffix = \"member\" elif serverrole", "= None self.idmapdb = None self.secrets = None self.keytab = None self.dns_keytab =", "provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get", "in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx + 1 return", "file. :param path: Path to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\":", "try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain):", "msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] =", "= ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This is stored without path prefix", "dnsdomain: DNS Domain name \"\"\" paths = ProvisionPaths() paths.private_dir = lp.get(\"private dir\") #", "\"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and the policy folders beneath. :param sysvol:", "hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg)", "DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls", "\"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"),", "nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID,", "logger.info(\"Please install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the", "# We don't need to set msg[\"flatname\"] here, because rdn_name will handle #", "it just didn't exist --abartlet data = open(smbconf, 'r').read() data = data.lstrip() if", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for", "domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid,", "try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775) # we need to freeze", "499), }) # This is partially Samba4 specific and should be replaced by", "== \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname,", "idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param samdb:", ":param credentials: Credentials :param lp: Loadparm context :return: LDB handle for the created", "= ' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns,", "lowest USN modified by this upgrade :param high: The highest USN modified by", "setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"NEXTRID\":", "targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out a DNS zone", "# Setup fSMORoleOwner entries to point at the newly created DC entry setup_modify_ldif(samdb,", "= ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This", "the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is", "were set # on the provision/join command line are set in the resulting", "result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None,", "serverrole == \"standalone\": smbconfsuffix = \"standalone\" if sid_generator is None: sid_generator = \"internal\"", "None: if dnsdomain is None: dnsdomain = realm.lower() dnsname = '%s.%s' % (netbiosname.lower(),", "# as the upper range of the rIDAvailablePool is 1073741823 and # we", "of the LDIF file to load :param subst_vars: Optional variables to subsitute in", "the provision :param samdb: A LDB object pointing to the sam.ldb :param basedn:", "msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s' % shortname ] if", "hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain)", "\\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\", "find user/group in %r\" % names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid", "# team and/or release manager. They have a big impact on the whole", "\"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\":", "need # to know what level of AD we are emulating. # These", "#force the length to be <16 netbiosname = newnbname[0:15] else: netbiosname = hostname.upper()", "names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets database. :note: This", "name of the domain :param domaindn: The DN of the domain (ie. DC=...)", "names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill", "return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param samdb: Sam Database", "* 1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\":", "\"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid,", "os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to bind", "== \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type ==", "DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def", "is not None: privatedir_line = \"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line", "idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger,", "os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to cope with umask", "GID of the \"Domain adminstrators\" group :param domainsid: The SID of the domain", "\\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\", "or \"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users', 'other', 'staff']) if wheel is", "redistribute it and/or modify # it under the terms of the GNU General", "None self.samdb = None def check_install(lp, session_info, credentials): \"\"\"Check whether the current install", "folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files in", "\"\"\"Create a new smb.conf file based on a couple of basic settings. \"\"\"", "samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry from", "privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf lp.load(smbconf) # and dump it", "prefix for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab =", "the domain functionality levels onto the database. # Various module (the password_hash module", ": '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup", "\"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\") display_specifiers_ldif =", "match chosen realm '%s'! Please remove the smb.conf file and let provision generate", "directory :param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, {", "from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" %", "res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for", "hostip6 is not None: hostip6_base_line = \" IN AAAA \" + hostip6 hostip6_host_line", "except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in", "credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam", "path, acl, domsid) for root, dirs, files in os.walk(path, topdown=False): for name in", "hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname is", "netbiosname = hostname.upper() if serverrole is None: serverrole = \"standalone\" assert serverrole in", "global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD schema\") # Load the schema", "= os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb =", "user. :param nobody_uid: uid of the UNIX nobody user. :param users_gid: gid of", "dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend,", "is None or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not specified in supplied", "= \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\":", "\"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or \"users\", 'users', 'other',", "Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import b64encode import os import re", "An LDB object on the SAM db :param lp: an LP object \"\"\"", "else: sid_generator_line = \"sid generator = \" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"),", "\\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\", "GUID for default policy are described at # \"How Core Group Policy Works\"", "empty smb.conf gives, then we need to be smarter. # Pretend it just", "domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\",", "for GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid))", "# seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\":", "at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN update list", "samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to point", "\"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\":", "ensures that any smb.conf parameters that were set # on the provision/join command", "elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid,", "os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir,", "ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return the biggest USN", "supplied %s. Please remove the smb.conf file and let provision generate it\" %", "share, but you\" \" are configuring a DC.\") logger.info(\"Please either remove %s or", "of the policy :return: A string with the complete path to the policy", "paths.namedconf) logger.info(\"and %s for further documentation required for secure DNS \" \"updates\", paths.namedtxt)", "dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp):", "== netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not be equal to short host", "installed, your Samba4 server will be ready to use\") logger.info(\"Server Role: %s\" %", "the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list,", "any smb.conf parameters that were set # on the provision/join command line are", "later the following commandline to start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is", "False else: canchown = True # Set the SYSVOL_ACL on the sysvol folder", "but we don't delete the old record that we are about to modify,", "big impact on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None:", "Exception: secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb to disk secrets_ldb.transaction_commit() # the", "not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please", "= lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None,", "-1, paths.bind_gid) # chmod needed to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664)", "result.domaindn = domaindn result.paths = paths result.lp = lp result.samdb = samdb return", "def get_max_usn(samdb,basedn): \"\"\" This function return the biggest USN present in the provision", "names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr =", "<16 netbiosname = newnbname[0:15] else: netbiosname = hostname.upper() if serverrole is None: serverrole", "\\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\", "hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self, value):", "logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain,", "None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def", "targetdir is not None: privdir = os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\")", "for the sysvol folder :param gid: The GID of the \"Domain adminstrators\" group", "lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets =", "logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill ==", "lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\":", "+ dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not", "generator = \" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol,", "specific bits to a secrets database. :param secretsdb: Ldb Handle to the secrets", "= \"gc._msdcs IN A \" + hostip else: hostip_base_line = \"\" hostip_host_line =", "setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception:", "\"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\")", "data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF", "from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import ndr_pack,", "of the default domain policy :param policyguid_dc: GUID of the default domain controler", "machinepass: Machine password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if", "complex expression tries to ensure that we don't have more # than one", "else: hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns)", "\"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\"", "(ie. DC=foo, DC=bar) :return: The biggest USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn,", "= os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf,", "GUID of the policy :return: A string with the complete path to the", "if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not be equal to", "domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression tries to", "os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir,", "errors # loading an empty smb.conf gives, then we need to be smarter.", "enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this attribute does not exist", "DC=bar) :return: The biggest USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\",", "not be equal to hostname '%s'!\" % (realm, hostname)) if netbiosname.upper() == realm:", "# Set ACL for GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp,", "file to load :param subst_vars: Optional variables to subsitute in LDIF. :param nocontrols:", "to 'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() != domain: raise", "one record for this SID, realm or netbios domain at a time, #", "# because that would delete the keytab and previous password. res = secretsdb.search(base=\"cn=Primary", "a couple of basic settings. \"\"\" assert smbconf is not None if hostname", "hostname + \" IN AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA", "\"\"\"A generic provision error.\"\"\" def __init__(self, value): self.value = value def __str__(self): return", "logger=logger) elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger,", "dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path,", "except KeyError: bind_gid = None if targetdir is not None: smbconf = os.path.join(targetdir,", "setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names,", "File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\":", "ldb: LDB object. :param ldif_path: LDIF file path. :param subst_vars: Optional dictionary with", "SID of the domain :param domaindn: The DN of the domain (ie. DC=...)", "You should have received a copy of the GNU General Public License #", "None self.hkpd = None self.hkpt = None self.samdb = None self.idmapdb = None", "ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain,", "names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality),", "def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param samdb: Sam Database handle \"\"\"", "None self.dns_keytab = None self.dns = None self.winsdb = None self.private_dir = None", "\"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not", "\"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg =", "\"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\"", "as the upper range of the rIDAvailablePool is 1073741823 and # we don't", "acls on Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp)", "None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None:", "\"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions", "we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now we can connect to", "+ hostip6 else: hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if", "dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba 4 has been \"", "realm, }) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self, value): self.value =", "# Provision does not make much sense values larger than 1000000000 # as", "= Schema(domainsid, schemadn=names.schemadn) # Load the database, but don's load the global schema", "\"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\"", "if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\"))", "\\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\", "samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, )", "ATTENTION: Do NOT change these default values without discussion with the # team", "we # just want to wipe and re-initialise the database, not start it", "logger.info(\"Once the above files are installed, your Samba4 server will be ready to", "remove forbidden chars newnbname = \"\" for x in netbiosname: if x.isalnum() or", "\"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\"", "hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname is None: netbiosname =", "provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None,", "LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low,", "canchown = True # Set the SYSVOL_ACL on the sysvol folder and subfolder", "def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private dir. :param ldb:", "users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), {", "of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\":", "and let provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() !=", "raise def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database. :param path: Path to", "%s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: # now display slapd_command_file.txt to", "connect to sam.ldb :param low: The lowest USN modified by this upgrade :param", "\"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\"", ":param subst_vars: Optional variables to subsitute in LDIF. :param nocontrols: Optional list of", "= \" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(),", "domain name of the AD domain :param policyguid: GUID of the default domain", "SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import", "setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" :", "remove %s or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon", "hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we use no variable", "\"\"\"Add domain join-specific bits to a secrets database. :param secretsdb: Ldb Handle to", "the domain :param domaindn: The DN of the domain (ie. DC=...) :param samdb:", "domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf file based", "setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except", "create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting", "only install a new smb.conf if there isn't one there already if os.path.exists(smbconf):", "\"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\":", "setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain,", "}) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a file", "# DNS AD-style setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')),", "auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD schema\") #", "to find user/group in %r\" % names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2]", "if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass is None: machinepass", "ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this wipes all existing data!", "not found) :param names: Names to check. :return: Value return by first names", "samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None,", "\"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\"", "= os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm =", "hostname: Local hostname :param realm: Realm name :param domainguid: GUID of the domain.", "name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might", "# and dump it without any values that are the default # this", "\"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\":", "f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name", "None self.domaindn = None self.lp = None self.samdb = None def check_install(lp, session_info,", "policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None,", "self.hku = None self.hkpd = None self.hkpt = None self.samdb = None self.idmapdb", "provision to figure out if the field have been modified since last provision.", "ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function", "\"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def", "the GNU General Public License as published by # the Free Software Foundation;", "\"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\":", "to load :param subst_vars: Optional variables to subsitute in LDIF. :param nocontrols: Optional", "needed to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if not", "values without discussion with the # team and/or release manager. They have a", "is None: domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt the group", "b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line })", "you are configuring a DC.\") logger.info(\"Please either remove %s or see the template", "chown %s to bind gid %u\" % ( dns_dir, paths.bind_gid)) if targetdir is", "\"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid,", "\"named\"]) except KeyError: bind_gid = None if targetdir is not None: smbconf =", "suitable for Samba 4 has been \" \"generated at %s\", paths.krb5conf) if serverrole", "\" IN A \" + hostip gc_msdcs_ip_line = \"gc._msdcs IN A \" +", "secure_channel_type=SEC_CHAN_BDC) # Now set up the right msDS-SupportedEncryptionTypes into the DB # In", "\"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\"", "lp, session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the partitions for the SAM", "dnsdomain, private_dir, keytab_name): \"\"\"Write out a file containing zone statements suitable for inclusion", "policy given its guid. :param sysvolpath: Path to the sysvol folder :param dnsdomain:", "the global schema and don't connect # quite yet samdb = SamDB(session_info=session_info, url=None,", "\"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>,", "secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info,", "into the DB # In future, this might be determined from some configuration", "None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm)", "= None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field provisionUSN in sam.ldb", "policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE", "domainsid, domaindn, samdb, lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None,", "samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\"", "private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a file containing zone", "lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn()", "# And now we can connect to the DB - the schema won't", "domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to", "And now we can connect to the DB - the schema won't be", "if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set", "useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if", "secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\"))", "== 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except", "= samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest", "does not handle exceptions and transaction on purpose, it's up to the caller", "GUID of the default domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path", "samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit()", "to disk secrets_ldb.transaction_commit() # the commit creates the dns.keytab, now chown it dns_keytab_path", "if provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try:", "findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def", "== \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname,", "the idmap database. :param path: path to the idmap database :param session_info: Session", "= re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx =", "domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate domain admin admin_session_info", "paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root,", "paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\")", "os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp):", "dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA", "== SEC_CHAN_BDC and dnsname is not None: # we are a domain controller", "domainguid_line = \"objectGUID: %s\\n-\" % domainguid else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid))", "= hostname.upper() if serverrole is None: serverrole = \"standalone\" assert serverrole in (\"domain", "join-specific bits to a secrets database. :param secretsdb: Ldb Handle to the secrets", "paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp)", "provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path,", "for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn", "hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname,", "delete the keytab and previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" %", "if domaindn is None: domaindn = \"DC=\" + netbiosname if not valid_netbios_name(domain): raise", "if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #", "= Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials,", "spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific", "logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is", "msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass", "USN present in the provision :param samdb: A LDB object pointing to the", "\" + hostip6 hostip6_host_line = hostname + \" IN AAAA \" + hostip6", "is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn result.paths", "logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn})", "# to know what level of AD we are emulating. # These will", "os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def", "netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to", "configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None,", "\"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\"", "names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality),", "a LDB handle, optionally substituting variables. :note: Either all LDIF data will be", "os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls on", "= findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None if targetdir is not None:", "}) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\":", "module in particular) need # to know what level of AD we are", "This is stored without path prefix for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\".", "None: hostip_base_line = \" IN A \" + hostip hostip_host_line = hostname +", "logger, paths): \"\"\"Write out a dns_update_list file\"\"\" # note that we use no", "= \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain = domain names.realm = realm", "% names.domaindn) # impersonate domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid", "names. :param samdb: SamDB object. :param idmap: IDmap db object. :param sid: The", "error = \"You want to run SAMBA 4 with a next_rid of %u,", "None: dnsdomain = realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname =", "valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is not", "\"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\":", "= os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path =", "ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\": names.configdn,", "\"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc })", ":param credentials: Credentials :param lp: Loadparm context \"\"\" reg = samba.registry.Registry() hive =", "invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None,", "\"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\")", "dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend,", "str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn})", "random password between Samba and it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is", "\"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "%s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"),", "Free Software Foundation; either version 3 of the License, or # (at your", "%s or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is", "setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\":", "-> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\":", "users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the", "None: sid_generator = \"internal\" assert domain is not None domain = domain.upper() assert", "serverrole = lp.get(\"server role\") assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if", "len(hostips) == 0: logger.warning(\"No external IPv4 address has been found. Using loopback.\") hostip", "None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to cope", "\"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\":", "1: logger.warning(\"More than one IPv4 address found. Using %s.\", hostip) if serverrole is", ":param domaindn: The domain DN. :param root_uid: uid of the UNIX root user.", "chosen domain '%s'! Please remove the %s file and let provision generate it\"", "b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\":", "info in the current database. :param paths: paths object :param dnsdomain: DNS Domain", "= None self.domain = None self.hostname = None self.sitename = None self.smbconf =", "creates the dns.keytab, now chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and", "'127.0.0.1' else: hostip = hostips[0] if len(hostips) > 1: logger.warning(\"More than one IPv4", "General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #", "\"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend,", "of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid", "+ \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir,", "adminpass = samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255) if", "dnsdomain: DNS name of the AD domain :param guid: The GUID of the", "os.chown(sysvol, -1, gid) except OSError: canchown = False else: canchown = True #", "in %s must match chosen realm '%s'! Please remove the smb.conf file and", "targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf file based on a couple", "+ 499), }) # This is partially Samba4 specific and should be replaced", "= samba.generate_random_password(128, 255) if ldapadminpass is None: # Make a new, random password", "wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path,", "for a domain :param sysvolpath: Physical path for the sysvol folder :param dnsdomain:", "session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info,", "secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is", "the field have been modified since last provision. :param samdb: An LDB object", "# Set acls on Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn,", "paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip is None: logger.info(\"Looking up", "of basic settings. \"\"\" assert smbconf is not None if hostname is None:", "names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), {", "logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm,", "\".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\")", "# and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not", "\"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update })", "+ rootdn if schemadn is None: schemadn = \"CN=Schema,\" + configdn if sitename", "which may not be stored locally but in LDAP. \"\"\" assert session_info is", "# loading an empty smb.conf gives, then we need to be smarter. #", "privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param path: Path to the", "must not be equal to short domain name '%s'!\" % (realm, domain)) if", "\\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "provisionUSN in sam.ldb This field is used to track range of USN modified", "entries for the keytab code to update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"]", "not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit()", "return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL =", "hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden chars", "= netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain =", "lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is None: serverrole = lp.get(\"server role\") if", "its guid. :param sysvolpath: Path to the sysvol folder :param dnsdomain: DNS name", "server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type = \"ldb\" sid_generator = \"internal\"", "if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) })", "mappings for sam names to unix names. :param samdb: SamDB object. :param idmap:", "[res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"]", "[\"top\", \"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"]", "DNS name of the domain :param domainsid: The SID of the domain :param", "name in dirs: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL,", "create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list file\"\"\" # note that we use", "+ 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), {", "if targetdir is not None: privdir = os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private", "\"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid =", "IPv6 IP :param hostname: Local hostname :param realm: Realm name :param domainguid: GUID", "str) # Setup fSMORoleOwner entries to point at the newly created DC entry", "from samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version,", "\"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] =", "= str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] =", "template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None if not", "backend type selected\") provision_backend.init() provision_backend.start() # only install a new shares config db", "if schema is None: schema = Schema(domainsid, schemadn=names.schemadn) # Load the database, but", "import urllib import shutil import ldb from samba.auth import system_session, admin_session import samba", "to the LDIF file. :param subst_vars: Dictionary with substitution variables. \"\"\" assert ldb", "Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid = DEFAULT_POLICY_GUID", "valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not", "machinepass is None: machinepass = samba.generate_random_password(128, 255) if dnspass is None: dnspass =", "None class ProvisionResult(object): def __init__(self): self.paths = None self.domaindn = None self.lp =", "is None: logger.info(\"Existing smb.conf does not have a [netlogon] share, but you are", "names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets database. :note:", "contexts and other important objects # \"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid):", "setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\"", "# ATTENTION: Do NOT change these default values without discussion with the #", "setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb,", "gives, then we need to be smarter. # Pretend it just didn't exist", "make a zone file on the first DC, it should be # replicated", "os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets", "setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time()", "substituting variables. :note: Either all LDIF data will be added or none (using", "or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) # force the", "= samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None,", "nobody_uid: uid of the UNIX nobody user. :param users_gid: gid of the UNIX", "if paths.netlogon is None: logger.info(\"Existing smb.conf does not have a [netlogon] share, but", "it's LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type = \"ldb\" sid_generator", "os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p):", "group :param domainsid: The SID of the domain :param dnsdomain: The DNS name", "+ hostip6 hostip6_host_line = hostname + \" IN AAAA \" + hostip6 gc_msdcs_ip6_line", "\"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" +", "realm names.netbiosname = netbiosname names.hostname = hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\"", "newnbname = \"%s%c\" % (newnbname, x) #force the length to be <16 netbiosname", "of the UNIX root user. :param nobody_uid: uid of the UNIX nobody user.", "range.append(tab[1]) idx = idx + 1 return range else: return None class ProvisionResult(object):", "AD domain :param guid: The GUID of the policy :return: A string with", "administrator account found\") def findnss(nssfn, names): \"\"\"Find a user or group from a", "logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc,", "+ \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain,", "name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class", "the UNIX root user. :param nobody_uid: uid of the UNIX nobody user. :param", "existing data, which may not be stored locally but in LDAP. \"\"\" assert", "them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid)", "domain = domain.upper() assert realm is not None realm = realm.upper() if lp", "provision() may call this, and then populate the database. :note: This will wipe", "terms of the GNU General Public License as published by # the Free", "modified by a provision or an upgradeprovision :param sam: An LDB object pointing", "SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE)", "SamDB object. :param idmap: IDmap db object. :param sid: The domain sid. :param", "DC function level (2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level", "there already if os.path.exists(smbconf): # if Samba Team members can't figure out the", "raise else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS =", "controller\": if domain is None: # This will, for better or worse, default", "name '%s'!\" % (domain, netbiosname)) else: domain = netbiosname if domaindn is None:", "This will wipe the Sam Database! :note: This function always removes the local", "hostip6 else: hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if hostip", "database. :param session_info: Session info. :param credentials: Credentials :param lp: Loadparm context :return:", "samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole", "is 1073741823 and # we don't want to create a domain that cannot", "on a couple of basic settings. \"\"\" assert smbconf is not None if", "Path of the LDIF file to load :param subst_vars: Optional variables to subsitute", "\" \"generated at %s\", paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths)", "\"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid +", "\"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password())", "if lastProvisionUSNs is not None: update_provision_usn(samdb, 0, maxUSN, 1) else: set_provision_usn(samdb, 0, maxUSN)", "\"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "domain DN. :param root_uid: uid of the UNIX root user. :param nobody_uid: uid", "if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name", "samdb.set_schema(schema) # Set the NTDS settings DN manually - in order to have", "\"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\"", "\"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass,", "> 1000000000: error = \"You want to run SAMBA 4 with a next_rid", "el in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn", "if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA 4 on a", "= \"\" for x in netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname", "IN A \" + hostip else: hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line", "secretsdb: Ldb Handle to the secrets database :param machinepass: Machine password \"\"\" attrs", "= Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the registry.", "Samba4 server will be ready to use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname:", "wipes all existing data! \"\"\" if domainsid is None: domainsid = security.random_sid() else:", "SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path,", "= [] idx = 0 p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab", "raise ProvisioningError(\"You want to run SAMBA 4 on a domain and forest function", "hostip gc_msdcs_ip_line = \"gc._msdcs IN A \" + hostip else: hostip_base_line = \"\"", "\"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\"", "logger.info(\"Existing smb.conf does not have a [netlogon] share, but you are configuring a", "to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'):", "= security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm", "gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in dirs: if canchown: os.chown(os.path.join(root,", "and let provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None:", "def get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by a provision or an upgradeprovision", "paths.netlogon is None: logger.info(\"Existing smb.conf does not have a [netlogon] share, but you", "\"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\")", "program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level", "WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS", "or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\")", "1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn,", "lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None,", "rids. if next_rid < 1000 or next_rid > 1000000000: error = \"You want", "samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the", "manually - in order to have it already around # before the provisioned", "root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res =", "a domain controller then we add servicePrincipalName # entries for the keytab code", "= \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path to the", "idx = idx + 1 return range else: return None class ProvisionResult(object): def", "Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) != 1:", "def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL for", "netlogon: Physical path for the netlogon folder :param sysvol: Physical path for the", "machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger", "The GUID of the policy :return: A string with the complete path to", "nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel)", "def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\"", "variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import", "there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info,", "realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See", "= None def check_install(lp, session_info, credentials): \"\"\"Check whether the current install seems ok.", "domaindn is None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname:", "hostip6_host_line = hostname + \" IN AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs", "\"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out", "os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if", "a Samba4 server # Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME>", "credentials: Credentials :param lp: Loadparm context :return: LDB handle for the created secrets", ":param lp: Loadparm context :param session_info: Session information :param credentials: Credentials \"\"\" if", "None self.hkcu = None self.hkcr = None self.hku = None self.hkpd = None", "backend_type = \"ldb\" sid_generator = \"internal\" if backend_type == \"fedora-ds\": sid_generator = \"backend\"", "ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole", "sam.ldb :param basedn: A string containing the base DN of the provision (ie.", "create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba 4 has been", "import setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend import ( ExistingBackend,", "groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\":", "credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD schema\") # Load", "def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for provisioning. :param lp: Loadparm context.", "data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"DOMAINDN\":", "in files: setntacl(lp, os.path.join(root, name), acl, domsid) for name in dirs: setntacl(lp, os.path.join(root,", "import logging import time import uuid import socket import urllib import shutil import", "\"DESCRIPTOR\": descr, }) # The LDIF here was created when the Schema object", "do this job. :param path: Path to the secrets database. :param session_info: Session", "the new named.conf file. :param dnsdomain: DNS Domain name :param hostname: Local hostname", "Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\"))", "AD schema\") # Load the schema from the one we computed earlier samdb.set_schema(schema)", "if hostip6 is not None: hostip6_base_line = \" IN AAAA \" + hostip6", "except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None,", "\"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf lp.load(smbconf) #", "team and/or release manager. They have a big impact on the whole program!", "else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for", "+ hostip else: hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir", "\"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid):", "findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb", "realm = realm.upper() if lp is None: lp = samba.param.LoadParm() #Load non-existant file", "runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN update list setup_file(setup_path(\"spn_update_list\"),", "names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID:", "USN modified by a provision or an upgradeprovision :param sam: An LDB object", "the main SAM database file! \"\"\" # Provision does not make much sense", "of the rIDAvailablePool is 1073741823 and # we don't want to create a", "configdn if sitename is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn names.domaindn", "netbiosname = hostname # remove forbidden chars newnbname = \"\" for x in", "= \"\" if hostip is not None: hostip_base_line = \" IN A \"", "\"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version,", "the database # modifictions below, but we need them set from the start.", "assert isinstance(domainguid, str) # Only make a zone file on the first DC,", "realm is not None: if dnsdomain is None: dnsdomain = realm.lower() dnsname =", "containing zone statements suitable for inclusion in a named.conf file (including GSS-TSIG configuration).", "is None: machinepass = samba.generate_random_password(128, 255) if dnspass is None: dnspass = samba.generate_random_password(128,", "assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database. :param path:", "ProvisioningError(\"No administrator account found\") def findnss(nssfn, names): \"\"\"Find a user or group from", "% names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam,", "from samba.auth import system_session, admin_session import samba from samba import ( Ldb, check_all_substituted,", "created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path):", "setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn})", "ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type", "\"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out", "that it will be useful, # but WITHOUT ANY WARRANTY; without even the", "\" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was not a valid NetBIOS", "USN modified by provision and upgradeprovision. This value is used afterward by next", "name :param private_dir: Path to private directory :param keytab_name: File name of DNS", "os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database. :param path: path", "the smb.conf file and let provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if", "= \"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir,", "% adminpass) if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP", "str(domainsid)) for root, dirs, files in os.walk(sysvol, topdown=False): for name in files: if", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not None: try:", "\"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\")", "# just want to wipe and re-initialise the database, not start it up", "from the info in the current database. :param paths: paths object :param dnsdomain:", "provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now", "% (newnbname, x) #force the length to be <16 netbiosname = newnbname[0:15] else:", "the hope that it will be useful, # but WITHOUT ANY WARRANTY; without", "\"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we use no", "not start it up try: os.unlink(samdb_path) except OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info,", "return samdb samdb.transaction_start() try: # Set the domain functionality levels onto the database.", "have a big impact on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level", "\"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), #", "don't want to create a domain that cannot allocate rids. if next_rid <", "dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) })", "provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting", "\"\"\"Return the physical path of policy given its guid. :param sysvolpath: Path to", "names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), #", "secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid,", "use options=[\"modules:\"] to stop the modules loading - we # just want to", "'HOST/%s' % shortname ] if secure_channel_type == SEC_CHAN_BDC and dnsname is not None:", "of the domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except OSError: canchown", "{ \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s'", "am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf", "DC.\") logger.info(\"Please either remove %s or see the template at %s\" % (paths.smbconf,", "= lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s'", "\"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\")", "dirs, files in os.walk(path, topdown=False): for name in files: setntacl(lp, os.path.join(root, name), acl,", "for root, dirs, files in os.walk(path, topdown=False): for name in files: setntacl(lp, os.path.join(root,", "Descriptors of naming contexts and other important objects # \"get_schema_descriptor\" is located in", "not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO", "-1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to cope with umask os.chmod(dns_dir,", "\"ldb\" sid_generator = \"internal\" if backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid =", "admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line = \"objectGUID: %s\\n-\" %", "== FILL_DRS: return samdb samdb.transaction_start() try: # Set the domain functionality levels onto", "= \"ldb\" sid_generator = \"internal\" if backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid", "import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\"", "def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the secrets database. :note: This function does", "ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match chosen domain '%s'! Please remove the", "on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level =", "by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts and other important", "FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\":", "LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return the biggest USN present in", "= [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]]", "msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass", "= \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path,", "import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry from samba.schema", "# Load the schema from the one we computed earlier samdb.set_schema(schema) # Set", "Domain '%s' must not be equal to short host name '%s'!\" % (domain,", "FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid, users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain", "removes the local SAM LDB file. The erase parameter controls whether to erase", "paths for provisioning. :param lp: Loadparm context. :param dnsdomain: DNS Domain name \"\"\"", "Alternatively, provision() may call this, and then populate the database. :note: This will", "to private directory :param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"),", "raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1,", "dnsdomain is None: dnsdomain = lp.get(\"realm\") if dnsdomain is None or dnsdomain ==", "equal to short domain name '%s'!\" % (realm, domain)) if rootdn is None:", "domsid) for name in dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain,", "setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname,", "= \"\" else: sid_generator_line = \"sid generator = \" + sid_generator sysvol =", "domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create", "ok. :param lp: Loadparm context :param session_info: Session information :param credentials: Credentials \"\"\"", "raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen realm '%s'! Please remove the", "adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None,", "f = open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid,", "canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls", "assert paths.netlogon is not None if paths.sysvol is None: logger.info(\"Existing smb.conf does not", "domain controller then we add servicePrincipalName # entries for the keytab code to", "\"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf =", "a provision or an upgradeprovision :param sam: An LDB object pointing to the", "= idx + 1 return range else: return None class ProvisionResult(object): def __init__(self):", "if not found) :param names: Names to check. :return: Value return by first", "smbconfsuffix), smbconf, { \"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon,", "domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the right", "is not None: hostip_base_line = \" IN A \" + hostip hostip_host_line =", "x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #force the length to", "realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a file containing zone statements suitable for", "raise ProvisioningError(\"guess_names: 'server role' not specified in supplied %s!\" % lp.configfile) serverrole =", "str(int(time.time() * 1e7)), # seconds -> ticks \"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn,", "<NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C) <NAME>", ":param nocontrols: Optional list of controls, can be None for no controls \"\"\"", "for the sysvol folder :param dnsdomain: DNS domain name of the AD domain", "or appended (default) \"\"\" tab = [] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\"", "provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\":", "idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb =", "names.serverdn) # And now we can connect to the DB - the schema", "else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\":", "ProvisioningError(\"guess_names: 'server role=%s' in %s must match chosen server role '%s'! Please remove", "controller\", \"member server\", \"standalone\") if serverrole == \"domain controller\": smbconfsuffix = \"dc\" elif", "# reload the smb.conf lp.load(smbconf) # and dump it without any values that", "setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF here was", "VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) # force the length to be", "__init__(self): self.paths = None self.domaindn = None self.lp = None self.samdb = None", "\\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line = \"\" if sid_generator == \"internal\": sid_generator_line", "names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass,", "bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located at %s", "idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def", "of the domain :param domainsid: The SID of the domain :param domaindn: The", "create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration include file", "= ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high):", "lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS settings DN manually - in order", "file based on a couple of basic settings. \"\"\" assert smbconf is not", "path to the policy folder \"\"\" if guid[0] != \"{\": guid = \"{%s}\"", "samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate domain admin admin_session_info =", "dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits to a secrets database. :param secretsdb:", "would delete the keytab and previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\"", "Path to the LDIF file. :param subst_vars: Dictionary with substitution variables. \"\"\" assert", "it, and it causes problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\"", "raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set", "up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info,", "not None: privdir = os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir,", "secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database. :param path: Path", "ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb to disk secrets_ldb.transaction_commit()", "\"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr", "names.realm = realm names.netbiosname = netbiosname names.hostname = hostname names.sitename = sitename names.serverdn", "name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm,", "return names def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create", "lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba 4 and AD schema\") # Load the", "file and let provision generate it\" % lp.configfile) if lp.get(\"realm\").upper() != realm: raise", "getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names, logger,", "data will be added or none (using transactions). :param ldb: LDB file to", "= None self.netbiosname = None self.domain = None self.hostname = None self.sitename =", "findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or \"users\",", "the Schema object was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema()", "the DB - the schema won't be loaded from the # DB samdb.connect(path)", "more details. # # You should have received a copy of the GNU", "\"domain controller\": smbconfsuffix = \"dc\" elif serverrole == \"member server\": smbconfsuffix = \"member\"", "domainguid, ntdsguid): \"\"\"Write out a DNS zone file, from the info in the", ":return: LDB handle for the created secrets database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path", "msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"]", ":param samdb: An LDB object on the SAM db :param lp: an LP", "upgradeprovision :param sam: An LDB object pointing to the sam.ldb :return: an integer", "policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\",", "samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def get_last_provision_usn(sam): \"\"\"Get the lastest USN", "not a valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r'", "LDB object on the SAM db :param lp: an LP object \"\"\" #", "The biggest USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"])", "if netbiosname is None: netbiosname = hostname # remove forbidden chars newnbname =", "res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin configuration", "= None self.hkcr = None self.hku = None self.hkpd = None self.hkpt =", "exist in this schema raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir,", "is not None: privdir = os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\",", "the secrets.ldb to disk secrets_ldb.transaction_commit() # the commit creates the dns.keytab, now chown", "\\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec", "domain join-specific bits to a secrets database. :param secretsdb: Ldb Handle to the", "of %u, \" % (next_rid) error += \"the valid range is %u-%u. The", "= '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname = netbiosname.lower() #", "secrets database :param machinepass: Machine password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\",", "None if targetdir is not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf", ":param hostip6: Local IPv6 IP :param hostname: Local hostname :param realm: Realm name", "setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the", "users and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\":", "not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" %", "LDB object. :param ldif_path: LDIF file path. :param subst_vars: Optional dictionary with substitution", "logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname) logger.info(\"NetBIOS Domain: %s\" %", "hope that it will be useful, # but WITHOUT ANY WARRANTY; without even", "netbiosname is None: netbiosname = hostname # remove forbidden chars newnbname = \"\"", "policyguid.upper() if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass", "contents if targetdir is None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc + \"", "file if os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if targetdir is not", "= [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] =", "dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\": if paths.netlogon", "IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import", "dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm,", "server\", \"standalone\") if invocationid is None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir): os.mkdir(paths.private_dir)", "of the domain :param dnsdomain: The DNS name of the domain :param domaindn:", "= \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\")", "domainsid: The SID of the domain :param domaindn: The DN of the domain", "policyguid, policyguid_dc): \"\"\"Create the default GPO for a domain :param sysvolpath: Physical path", "\"\"\" This function return the biggest USN present in the provision :param samdb:", "secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add DNS specific bits", "lp.configfile)) if serverrole == \"domain controller\": if domain is None: # This will,", "None class ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn = None self.configdn =", "modified since last provision. :param samdb: An LDB object connect to sam.ldb :param", "if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf if there isn't", ":param users_gid: gid of the UNIX users group. :param wheel_gid: gid of the", "not handle exceptions and transaction on purpose, it's up to the caller to", "# Based on the original in EJS: # Copyright (C) <NAME> <<EMAIL>> 2005", "the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\":", "handle, optionally substituting variables. :note: Either all LDIF data will be added or", "logger.info(\"Pre-loading the Samba 4 and AD schema\") # Load the schema from the", "user or group from a list of possibilities. :param nssfn: NSS Function to", "inclusion in a named.conf file (including GSS-TSIG configuration). :param paths: all paths :param", "{\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid,", "file. :param dnsdomain: DNS Domain name :param hostname: Local hostname :param realm: Realm", "import security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import (", "%s\\n-\" % domainguid else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), {", "DNS name of the domain :param domaindn: The DN of the domain (ie.", "\"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\":", "the smb.conf file and let provision generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile))", "msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This", "\"\"\"A specified name was not a valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName,", "lp): \"\"\"Setup the privileges database. :param path: Path to the privileges database. :param", "'.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\":", "GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res", "\"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise", "smb.conf file and let provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server", "up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\")", "isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\"", "schemadn is None: schemadn = \"CN=Schema,\" + configdn if sitename is None: sitename=DEFAULTSITE", "Loadparm context. :param dnsdomain: DNS Domain name \"\"\" paths = ProvisionPaths() paths.private_dir =", "os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None: privatedir_line = \"private dir = \"", "guid) return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write(", "hostip) if serverrole is None: serverrole = lp.get(\"server role\") assert serverrole in (\"domain", "GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.", "lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges", "ProvisioningError(\"guess_names: 'realm =' was not specified in supplied %s. Please remove the smb.conf", "for further documentation required for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb)", "make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf", "raise KeyError if not found) :param names: Names to check. :return: Value return", "if sid_generator == \"internal\": sid_generator_line = \"\" else: sid_generator_line = \"sid generator =", "configuration settings to use.\"\"\" if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname =", "sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note:", "def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path of policy given its guid.", "Credentials :param lp: Loadparm context :return: LDB handle for the created secrets database", "names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600),", "names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting", "hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if hostip is not", "b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(), \"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) })", "domain :param sysvolpath: Physical path for the sysvol folder :param dnsdomain: DNS domain", "\\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl,", "policy folders beneath. :param sysvol: Physical path for the sysvol folder :param dnsdomain:", "partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\":", "config db if there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb", "configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import b64encode import os import re import", "levels onto the database. # Various module (the password_hash module in particular) need", "topdown=False): for name in files: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root,", "but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb, setup_path(\"secrets_sasl_ldap.ldif\"), { \"LDAPADMINUSER\": backend_credentials.get_username(),", "= None self.ldapmanagerdn = None self.dnsdomain = None self.realm = None self.netbiosname =", "described at # \"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is", "Handle to the secrets database :param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path))", "Machine password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm", "is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname is None:", "created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\":", "hostname + \" IN A \" + hostip gc_msdcs_ip_line = \"gc._msdcs IN A", "%u.\" % ( 1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do NOT change", "{ \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def", "\\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\", "the caller to do this job. :param path: Path to the secrets database.", "information :param credentials: Credentials :param lp: Loadparm context \"\"\" reg = samba.registry.Registry() hive", "% str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type", "\"domain controller\": if paths.netlogon is None: logger.info(\"Existing smb.conf does not have a [netlogon]", "database \"\"\" if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path", "= newnbname[0:15] else: netbiosname = hostname.upper() if serverrole is None: serverrole = \"standalone\"", "to unix names. :param samdb: SamDB object. :param idmap: IDmap db object. :param", "reasonable name mappings for sam names to unix names. :param samdb: SamDB object.", "the domain (ie. DC=...) :param samdb: An LDB object on the SAM db", "dnsdomain, hostname, realm): \"\"\"Write out a file containing zone statements suitable for inclusion", "loopback.\") hostip = '127.0.0.1' else: hostip = hostips[0] if len(hostips) > 1: logger.warning(\"More", "is free software; you can redistribute it and/or modify # it under the", "update the contents if targetdir is None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc", "Credentials :param lp: Loadparm context \"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info,", "configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid = bind_gid if hostip", "return by first names list. \"\"\" for name in names: try: return nssfn(name)", "gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls on Policy folder and", "if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid", "UNIX root user. :param nobody_uid: uid of the UNIX nobody user. :param users_gid:", "purpose, it's up to the caller to do this job. :param path: Path", "\"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the smb.conf lp.load(smbconf) # and dump", "domain :param policyguid: GUID of the default domain policy :param policyguid_dc: GUID of", "names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn,", "samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc,", "container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\":", "root, dirs, files in os.walk(path, topdown=False): for name in files: setntacl(lp, os.path.join(root, name),", "\"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\":", "def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new", "str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set", "= OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port,", "a new smb.conf file based on a couple of basic settings. \"\"\" assert", "for the sysvol share and the subfolders :param samdb: An LDB object on", "= samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass", "hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) # note that we use", "record. \"\"\" assert isinstance(domainguid, str) if hostip6 is not None: hostip6_base_line = \"", "if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s'", "serverrole = \"standalone\" assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if serverrole", "the partitions for the SAM database. Alternatively, provision() may call this, and then", "when the Schema object was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify)", "= \" IN AAAA \" + hostip6 hostip6_host_line = hostname + \" IN", "from samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl", "sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\", "hostname '%s'!\" % (realm, hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s'", ":param lp: Loadparm context :return: LDB handle for the created secrets database \"\"\"", "for x in netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\"", "install seems ok. :param lp: Loadparm context :param session_info: Session information :param credentials:", "later version. # # This program is distributed in the hope that it", ":note: Either all LDIF data will be added or none (using transactions). :param", "setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line,", "ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def", "None: domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt the group policy", "sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #force the length to be", "a PHP LDAP admin configuration file. :param path: Path to write the configuration", "paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path", "sysvol: Physical path for the sysvol folder :param gid: The GID of the", "\\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\", "realm): \"\"\"Write out a file containing zone statements suitable for inclusion in a", "[realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"]", "p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx + 1 return range else: return None", "to the privileges database. :param session_info: Session info. :param credentials: Credentials :param lp:", "\"\"\"Set the default paths for provisioning. :param lp: Loadparm context. :param dnsdomain: DNS", "\\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\", "the private dir. :param ldb: LDB object. :param ldif_path: LDIF file path. :param", "scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta", "up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb", "None: serverrole = lp.get(\"server role\") assert serverrole in (\"domain controller\", \"member server\", \"standalone\")", "not make much sense values larger than 1000000000 # as the upper range", "if dnsdomain is None or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not specified", "+ \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain,", "subfolders :param samdb: An LDB object on the SAM db :param netlogon: Physical", ") from samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl,", "partially Samba4 specific and should be replaced by the correct # DNS AD-style", "computed earlier samdb.set_schema(schema) # Set the NTDS settings DN manually - in order", "subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private", "one or appended (default) \"\"\" tab = [] if not replace: entry =", "secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None:", "smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf", "= os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info,", "\"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(),", "return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges", "dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database. :note: This will wipe the", "expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to point at the", "of the domain :param domaindn: The DN of the domain (ie. DC=...) :param", "samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None)", "dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line = \"\" if sid_generator == \"internal\":", "1) else: set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable", "samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\" if", "file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts and other important objects", "os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap", "lp: an LP object \"\"\" # Set ACL for GPO root folder root_policy_path", "try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in msg: if el", "dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL)", "= \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol =", "domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None,", "hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to hostname", "nssfn(name) except KeyError: pass raise KeyError(\"Unable to find user/group in %r\" % names)", "= \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775)", ": '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the", "in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb,", "sysvol share and the subfolders :param samdb: An LDB object on the SAM", "\"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\"", "def check_install(lp, session_info, credentials): \"\"\"Check whether the current install seems ok. :param lp:", "controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new", "session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up", "\"standalone\": smbconfsuffix = \"standalone\" if sid_generator is None: sid_generator = \"internal\" assert domain", ":note: This function always removes the local SAM LDB file. The erase parameter", "% urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend", "if not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting", "# Pretend it just didn't exist --abartlet data = open(smbconf, 'r').read() data =", "of the UNIX nobody user. :param users_gid: gid of the UNIX users group.", "Path to the registry database :param session_info: Session information :param credentials: Credentials :param", "idmap database :param session_info: Session information :param credentials: Credentials :param lp: Loadparm context", "is None: dnsdomain = realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname", "if os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if targetdir is not None:", "\" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir = \" + os.path.abspath(targetdir) lp.set(\"lock", "is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), {", "is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else:", "set # on the provision/join command line are set in the resulting smb.conf", "(low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE,", "existing one or appended (default) \"\"\" tab = [] if not replace: entry", "len(hostips) > 1: logger.warning(\"More than one IPv4 address found. Using %s.\", hostip) if", "600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\":", "backend_type is None: backend_type = \"ldb\" sid_generator = \"internal\" if backend_type == \"fedora-ds\":", "ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\"", "lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass,", "ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn names.configdn = configdn names.schemadn = schemadn", "% names.serverdn) # And now we can connect to the DB - the", "+ \" IN AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \"", "session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and backend_credentials.authentication_requested()): if", "\"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path,", "(including GSS-TSIG configuration). :param paths: all paths :param realm: Realm name :param dnsdomain:", "tab = [] tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb,", "not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must", "names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials,", "raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\")) !=", "VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #force the length to be <16", "version. # # This program is distributed in the hope that it will", "forest function level which itself is higher than its actual DC function level", "or worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper()", "next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid =", "this schema raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain,", "= \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "path: Path to the secrets database. :param session_info: Session info. :param credentials: Credentials", "range = [] idx = 0 p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]:", "[] tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE]", "the secrets database :param machinepass: Machine password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\",", "adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole ==", "\" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line = \"\"", "than its actual DC function level (2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level", "Schema(domainsid, schemadn=names.schemadn) # Load the database, but don's load the global schema and", "samba.generate_random_password(128, 255) if machinepass is None: machinepass = samba.generate_random_password(128, 255) if dnspass is", "which itself is higher than its actual DC function level (2008_R2). This won't", "# GNU General Public License for more details. # # You should have", "the registry database :param session_info: Session information :param credentials: Credentials :param lp: Loadparm", "path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm,", "database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is None:", "level of AD we are emulating. # These will be fixed into the", "schema is None: schema = Schema(domainsid, schemadn=names.schemadn) # Load the database, but don's", "+ os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line = \"\" if", "if serverrole == \"domain controller\": smbconfsuffix = \"dc\" elif serverrole == \"member server\":", "= DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality:", "group from a list of possibilities. :param nssfn: NSS Function to try (should", "to be smarter. # Pretend it just didn't exist --abartlet data = open(smbconf,", "the ACL for the sysvol share and the subfolders :param samdb: An LDB", "'%s' in smb.conf must match chosen domain '%s'! Please remove the %s file", "this program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a Samba", "read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars): \"\"\"Import a LDIF a file", "guid = \"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path", "netbiosname = newnbname[0:15] else: netbiosname = hostname.upper() if serverrole is None: serverrole =", "os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\") paths.namedconf = os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir,", "\"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\":", "create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm,", "# now display slapd_command_file.txt to show how slapd must be # started next", "= Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try:", "KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in msg:", "non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb and not lp.get(\"posix:eadb\"): if targetdir is", "%s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn result.paths = paths result.lp =", "License, or # (at your option) any later version. # # This program", "file path. :param subst_vars: Optional dictionary with substitution variables. \"\"\" data = read_and_sub_file(ldif_path,", "setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a file containing", "the old record that we are about to modify, # because that would", "we need to be smarter. # Pretend it just didn't exist --abartlet data", "configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain", "# entries for the keytab code to update. spn.extend([ 'HOST/%s' % dnsname ])", "\"domain controller\": if domain is None: # This will, for better or worse,", "name :param hostname: Local hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, {", "keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write", "None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255)", "This value is used afterward by next provision to figure out if the", "admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line =", "the domain :param dnsdomain: The DNS name of the domain :param domaindn: The", "Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\" if provision_backend.type is", "SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE =", "(low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD,", "the License, or # (at your option) any later version. # # This", "this value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE])", "command\")) os.system(rndc + \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname,", "the smb.conf lp.load(smbconf) # and dump it without any values that are the", "\\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\", "None: hostip6_base_line = \" IN AAAA \" + hostip6 hostip6_host_line = hostname +", "samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\":", "try: # Set the domain functionality levels onto the database. # Various module", "set up the right msDS-SupportedEncryptionTypes into the DB # In future, this might", "__init__(self): self.shareconf = None self.hklm = None self.hkcu = None self.hkcr = None", "in the resulting smb.conf f = open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb,", "wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None,", "== \"member server\": smbconfsuffix = \"member\" elif serverrole == \"standalone\": smbconfsuffix = \"standalone\"", "logging import time import uuid import socket import urllib import shutil import ldb", "self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid)", "\"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\")", "\"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)),", "domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt the group policy GUIDs", ":param session_info: Session information :param credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\": raise", "schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain = domain names.realm", "\"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type ==", "sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening", "to create a domain that cannot allocate rids. if next_rid < 1000 or", "samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) # impersonate domain admin", "a next_rid of %u, \" % (next_rid) error += \"the valid range is", "\"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if len(samdb.search(\"(cn=Administrator)\"))", "rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if hostname", "paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list =", "ldb from samba.auth import system_session, admin_session import samba from samba import ( Ldb,", "This function does not handle exceptions and transaction on purpose, it's up to", "\"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if", "up the right msDS-SupportedEncryptionTypes into the DB # In future, this might be", "rootdse. :param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\":", "we need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality)", "of the UNIX users group. :param wheel_gid: gid of the UNIX wheel group.", "\"\": raise ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower()", "paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.erase()", "rIDAvailablePool is 1073741823 and # we don't want to create a domain that", "lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path,", "\\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", ":param names: Names to check. :return: Value return by first names list. \"\"\"", "machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a", "names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname,", "files in os.walk(path, topdown=False): for name in files: setntacl(lp, os.path.join(root, name), acl, domsid)", "names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100),", "and paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError:", "= os.path.join(paths.private_dir, \"named.conf\") paths.namedconf_update = os.path.join(paths.private_dir, \"named.conf.update\") paths.namedtxt = os.path.join(paths.private_dir, \"named.txt\") paths.krb5conf =", "replicated with DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm,", "update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not None: try: os.chown(dns_dir, -1,", "self.samdb = None def check_install(lp, session_info, credentials): \"\"\"Check whether the current install seems", "= findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except", "None self.schemadn = None self.ldapmanagerdn = None self.dnsdomain = None self.realm = None", "names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host", "data.lstrip() if data is None or data == \"\": make_smbconf(smbconf, hostname, domain, realm,", "os.mkdir(paths.private_dir) if not os.path.exists(os.path.join(paths.private_dir, \"tls\")): os.mkdir(os.path.join(paths.private_dir, \"tls\")) ldapi_url = \"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\")", ":param wheel_gid: gid of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\",", "= lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths def", "This will wipe the main SAM database file! \"\"\" # Provision does not", "netbiosname.lower() # We don't need to set msg[\"flatname\"] here, because rdn_name will handle", "generate it\" % lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s", "}) # note that we use no variable substitution on this file #", "LDAP admin configuration file. :param path: Path to write the configuration to. \"\"\"", "samdb: SamDB object. :param idmap: IDmap db object. :param sid: The domain sid.", "into the database via the database # modifictions below, but we need them", "wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res =", "FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def", "file specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts and", "= ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn names.configdn = configdn names.schemadn =", "\"\"\"Setup a complete SAM Database. :note: This will wipe the main SAM database", "paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr =", "= \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon", "or \"samdb.ldb\") paths.idmapdb = os.path.join(paths.private_dir, lp.get(\"idmap database\") or \"idmap.ldb\") paths.secrets = os.path.join(paths.private_dir, lp.get(\"secrets", "self.domaindn = None self.configdn = None self.schemadn = None self.ldapmanagerdn = None self.dnsdomain", "None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is None: adminpass =", "names.domaindn) # impersonate domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is", "for default policy are described at # \"How Core Group Policy Works\" #", "\"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path,", "shortname = netbiosname.lower() # We don't need to set msg[\"flatname\"] here, because rdn_name", "session_info, lp): \"\"\"Setup the registry. :param path: Path to the registry database :param", "ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"),", "secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm,", "= None self.smbconf = None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field", "but don's load the global schema and don't connect # quite yet samdb", "not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up sam.ldb", "\"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path):", "% (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain controller\": if domain is", "of controls, can be None for no controls \"\"\" assert isinstance(ldif_path, str) data", "names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path of policy given", "open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid, users_gid,", "netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the right msDS-SupportedEncryptionTypes into the", "the LDIF file. :param subst_vars: Dictionary with substitution variables. \"\"\" assert ldb is", "\"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid))", "# \"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid", "exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And now we can", "not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\":", "that this attribute does not exist in this schema raise if serverrole ==", "= \"standalone\" if sid_generator is None: sid_generator = \"internal\" assert domain is not", "self.dns = None self.winsdb = None self.private_dir = None class ProvisionNames(object): def __init__(self):", "\"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\":", "# Copyright (C) <NAME> <<EMAIL>> 2005 # # This program is free software;", "folder :param sysvol: Physical path for the sysvol folder :param gid: The GID", "\"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] =", "try: logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(),", "\"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec)", "DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from", "\\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\", "paths.namedconf, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\":", "pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError: pass for el in msg: if", "GPO for a domain :param sysvolpath: Physical path for the sysvol folder :param", "servicePrincipalName # entries for the keytab code to update. spn.extend([ 'HOST/%s' % dnsname", "try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials is not None and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not", "not None # We use options=[\"modules:\"] to stop the modules loading - we", "lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp,", "policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info,", "= \"CN=Configuration,\" + rootdn if schemadn is None: schemadn = \"CN=Schema,\" + configdn", "\\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "global schema and don't connect # quite yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False,", "is None: lp = samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb", "it's up to the caller to do this job. :param path: Path to", "main SAM database file! \"\"\" # Provision does not make much sense values", "names) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None,", "path for the netlogon folder :param sysvol: Physical path for the sysvol folder", "\"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path to the provision tempate file specified", "samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return the biggest USN present in the", "is not None if paths.sysvol is None: logger.info(\"Existing smb.conf does not have a", "raise ProvisioningError(\"No administrator account found\") def findnss(nssfn, names): \"\"\"Find a user or group", "LDB file to import into. :param ldif_path: Path to the LDIF file. :param", "domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown", "info. :param credentials: Credentials :param lp: Loadparm context :return: LDB handle for the", "str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb,", "names, schema, serverrole, erase=False): \"\"\"Setup the partitions for the SAM database. Alternatively, provision()", "the default domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc)", "attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to point at", "== \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf,", "caller to do this job. :param path: Path to the secrets database. :param", "\"named.txt\") paths.krb5conf = os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\")", "{ \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() *", "assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]):", "this upgrade :param high: The highest USN modified by this upgrade\"\"\" tab =", "- in order to have it already around # before the provisioned tree", "the subfolders :param samdb: An LDB object on the SAM db :param netlogon:", "# Set up group policies (domain policy and domain controller # policy) create_default_gpo(paths.sysvol,", "for BIND\", paths.namedconf) logger.info(\"and %s for further documentation required for secure DNS \"", "acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL on the", "{ \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting", "except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC =", "os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn, root_uid=root_uid, nobody_uid=nobody_uid,", "def __init__(self): self.shareconf = None self.hklm = None self.hkcu = None self.hkcr =", "Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" %", "lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None,", "netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) # reload the", "DN of the provision (ie. DC=foo, DC=bar) :return: The biggest USN in the", "if realm is not None: if dnsdomain is None: dnsdomain = realm.lower() dnsname", "the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) # and", "found\") def findnss(nssfn, names): \"\"\"Find a user or group from a list of", "\"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass,", "We don't need to set msg[\"flatname\"] here, because rdn_name will handle # it,", "display slapd_command_file.txt to show how slapd must be # started next time logger.info(\"Use", "None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\",", "lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths,", "users_gid: gid of the UNIX users group. :param wheel_gid: gid of the UNIX", "\"\"\"Get the lastest USN modified by a provision or an upgradeprovision :param sam:", "If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a Samba configuration.\"\"\" __docformat__", "domaindn is None: domaindn = \"DC=\" + netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain)", ":param dnsdomain: DNS Domain name :param hostname: Local hostname :param realm: Realm name", "dns_update_list file\"\"\" # note that we use no variable substitution on this file", "Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database. :param path:", "Local hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\":", "create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write out a file containing zone statements suitable for", "dir. :param ldb: LDB object. :param ldif_path: LDIF file path. :param subst_vars: Optional", "modify # it under the terms of the GNU General Public License as", "names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel()", "name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in dirs: if", "= lp.get(\"private dir\") # This is stored without path prefix for the \"privateKeytab\"", "'realm =' was not specified in supplied %s. Please remove the smb.conf file", "return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\")", "os.path.exists(smbconf): # if Samba Team members can't figure out the weird errors #", "discussion with the # team and/or release manager. They have a big impact", "= \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile", "logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\"", "a domain and forest function level which itself is higher than its actual", "SAM database file! \"\"\" # Provision does not make much sense values larger", "have more # than one record for this SID, realm or netbios domain", "-1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind", "if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for", "is not None: logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin", "value): self.value = value def __str__(self): return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception):", "A \" + hostip hostip_host_line = hostname + \" IN A \" +", "in names: try: return nssfn(name) except KeyError: pass raise KeyError(\"Unable to find user/group", "adminpass is None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass =", "len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]]", "See the # GNU General Public License for more details. # # You", "erase=False): \"\"\"Setup the partitions for the SAM database. Alternatively, provision() may call this,", "\"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\"", "data into :param ldif_path: Path of the LDIF file to load :param subst_vars:", "from samba.schema import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID", "slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type,", "= \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s'", "logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap", "your option) any later version. # # This program is distributed in the", "complete SAM Database. :note: This will wipe the main SAM database file! \"\"\"", "def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is not a valid NetBIOS", "%r\" % names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names:", "paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths,", "\"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, })", "in the private dir. :param ldb: LDB file to import data into :param", "None self.domaindn = None self.configdn = None self.schemadn = None self.ldapmanagerdn = None", "None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else: ntdsguid_line = \"\" setup_add_ldif(samdb, setup_path(\"provision_self_join.ldif\"), { \"CONFIGDN\":", "guid: The GUID of the policy :return: A string with the complete path", "ldapadminpass is None: # Make a new, random password between Samba and it's", "= None shortname = netbiosname.lower() # We don't need to set msg[\"flatname\"] here,", "findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private dir.", "\"\" hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if hostip is not None: hostip_base_line", "object connect to sam.ldb :param low: The lowest USN modified by this upgrade", "default GPO for a domain :param sysvolpath: Physical path for the sysvol folder", "= [] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE,", "The highest USN modified by this upgrade :param replace: A boolean indicating if", "delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta)", "\" IN AAAA \" + hostip6 gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" +", "= os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None: smbconf = samba.param.default_path() if not", "Either all LDIF data will be added or none (using transactions). :param ldb:", "assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if serverrole == \"domain controller\":", "}) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self, value): self.value = value", "can connect to the DB - the schema won't be loaded from the", "DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc =", "dnsdomain is None: dnsdomain = realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else:", "-> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\":", "lp = samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if eadb and not", "variable substitution on this file # the substitution is done at runtime by", "the weird errors # loading an empty smb.conf gives, then we need to", "Setup fSMORoleOwner entries to point at the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"),", "this attribute does not exist in this schema raise if serverrole == \"domain", "% (lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s'", "\"NETBIOS_NAME\": netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\":", "import uuid import socket import urllib import shutil import ldb from samba.auth import", "in order to have it already around # before the provisioned tree exists", "have a [sysvol] share, but you\" \" are configuring a DC.\") logger.info(\"Please either", "\\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn, lp): \"\"\"Set the ACL for the", "than one record for this SID, realm or netbios domain at a time,", "sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\"", "\"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message()", "populate the database. :note: This will wipe the Sam Database! :note: This function", "VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\"", "uuid import socket import urllib import shutil import ldb from samba.auth import system_session,", "idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend,", "setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) })", "DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\": gc_msdcs_ip6_line, }) #", "share and the subfolders :param samdb: An LDB object on the SAM db", "hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try:", "this SID, realm or netbios domain at a time, # but we don't", "}) # The LDIF here was created when the Schema object was constructed", "backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None, ol_mmr_urls=None, ol_olc=None, setup_ds_path=None, slapd_path=None, nosync=False,", "= os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640)", "have a [netlogon] share, but you are configuring a DC.\") logger.info(\"Please either remove", "up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\":", "set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies folder and", "expression tries to ensure that we don't have more # than one record", "is None: lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole,", ":param domainguid: GUID of the domain. :param ntdsguid: GUID of the hosts nTDSDSA", "settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(),", "serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid =", "emulating. # These will be fixed into the database via the database #", "\"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\"", "with a next_rid of %u, \" % (next_rid) error += \"the valid range", "ProvisioningError(\"guess_names: 'server role' not specified in supplied %s!\" % lp.configfile) serverrole = serverrole.lower()", "= security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\"", "paths.dns_update_list, None) # and the SPN update list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid", "not be stored locally but in LDAP. \"\"\" assert session_info is not None", "\"standalone\" assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if serverrole == \"domain", "provision_backend, lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid,", "\\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\", "reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\")", "if data is None or data == \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole,", "POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res:", "The DNS name of the domain :param domainsid: The SID of the domain", "assert isinstance(invocationid, str) if ntdsguid is not None: ntdsguid_line = \"objectGUID: %s\\n\"%ntdsguid else:", "provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" %", "the highest USN modified by (upgrade)provision, 0 is this value is unknown \"\"\"", "to hostname '%s'!\" % (realm, hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm", "getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid,", "raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to short domain name '%s'!\"", "= \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid):", "to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip,", "paths.bind_gid)) if targetdir is None: os.system(rndc + \" unfreeze \" + lp.get(\"realm\")) def", "= [\"%s$\" % netbiosname] msg[\"secureChannelType\"] = [str(secure_channel_type)] if domainsid is not None: msg[\"objectSid\"]", "LDB file to import data into :param ldif_path: Path of the LDIF file", "\",DC=\") if domain == netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not be equal", "this ensures that any smb.conf parameters that were set # on the provision/join", "we need to freeze the zone while we update the contents if targetdir", "setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns,", "\"hkcr.ldb\" paths.hkcu = \"hkcu.ldb\" paths.hku = \"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\"", "has been \" \"generated at %s\", paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp,", "% names.hostname) logger.info(\"NetBIOS Domain: %s\" % names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN", "os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\")", "self.dnsdomain = None self.realm = None self.netbiosname = None self.domain = None self.hostname", "names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid", "lastest USN modified by a provision or an upgradeprovision :param sam: An LDB", "}) def create_krb5_conf(path, dnsdomain, hostname, realm): \"\"\"Write out a file containing zone statements", "database # modifictions below, but we need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\",", "\"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;bc0ac240-79a9-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\"", "setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private dir. :param ldb: LDB", "reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup", "= samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to", "if os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir,", "= bind_gid if hostip is None: logger.info(\"Looking up IPv4 addresses\") hostips = samba.interface_ips(lp,", "basic settings. \"\"\" assert smbconf is not None if hostname is None: hostname", "setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn,", "domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings to use.\"\"\" if hostname is", "Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials,", "elif smbconf is None: smbconf = samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only", "os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775)", "invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn = \"CN=NTDS Settings,%s\"", "= \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\", "sam.ldb with new schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info,", "( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from", "try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to", "must match chosen domain '%s'! Please remove the %s file and let provision", "Set ACL for GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path,", "dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None, backend_type=None, sitename=None,", "samba.schema import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID =", "sid_generator_line = \"sid generator = \" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\")", "\"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>,", "smarter. # Pretend it just didn't exist --abartlet data = open(smbconf, 'r').read() data", "machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), {", "from samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID =", "paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1,", "database via the database # modifictions below, but we need them set from", "Samba 4 has been \" \"generated at %s\", paths.krb5conf) if serverrole == \"domain", "the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb,", "modified by provision and upgradeprovision. This value is used afterward by next provision", "setup_path(\"provision.reg\") assert os.path.exists(provision_reg) reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database. :param", "\"\" for x in netbiosname: if x.isalnum() or x in VALID_NETBIOS_CHARS: newnbname =", "password: %s\" % adminpass) if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not", "domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "== \"standalone\": smbconfsuffix = \"standalone\" if sid_generator is None: sid_generator = \"internal\" assert", "boolean indicating if the range should replace any existing one or appended (default)", "krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None,", "0775) os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown %s to", "DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name,", "idmap database. :param path: path to the idmap database :param session_info: Session information", "domain at a time, # but we don't delete the old record that", "( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return the physical path of", "= \"DC=\" + netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm:", "is not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None: smbconf", "logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\":", "!= 1: raise ProvisioningError(\"No administrator account found\") def findnss(nssfn, names): \"\"\"Find a user", "containing the base DN of the provision (ie. DC=foo, DC=bar) :return: The biggest", "3 of the License, or # (at your option) any later version. #", "not None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid else: domainguid_line = \"\" descr", "\"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\"", "= \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl, lp, domsid): setntacl(lp, path, acl,", "KeyError: pass for el in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn,", "not be equal to netbios hostname '%s'!\" % (realm, netbiosname)) if domain ==", "def setup_path(file): \"\"\"Return an absolute path to the provision tempate file specified by", "provision and upgradeprovision. This value is used afterward by next provision to figure", "sid_generator_line = \"\" else: sid_generator_line = \"sid generator = \" + sid_generator sysvol", "smb.conf lp.load(smbconf) # and dump it without any values that are the default", "wheel_gid: gid of the UNIX wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID,", "wipe and re-initialise the database, not start it up try: os.unlink(samdb_path) except OSError:", "dump it without any values that are the default # this ensures that", "we can connect to the DB - the schema won't be loaded from", "= None self.secrets = None self.keytab = None self.dns_keytab = None self.dns =", "guid[0] != \"{\": guid = \"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\",", "names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str)", "setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except Exception: samdb.transaction_cancel() raise else:", "\\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\", "== \"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"), session_info=session_info, credentials=credentials, lp=lp) if", "+ sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\"", "except OSError: pass os.mkdir(dns_dir, 0775) # we need to freeze the zone while", "# Descriptors of naming contexts and other important objects # \"get_schema_descriptor\" is located", "\"gc._msdcs IN A \" + hostip else: hostip_base_line = \"\" hostip_host_line = \"\"", "\"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\")", "policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\":", "\"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid,", "expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb", "This function return the biggest USN present in the provision :param samdb: A", "= getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol,", "smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, hostip=None, hostip6=None,", "path: Path to the privileges database. :param session_info: Session info. :param credentials: Credentials", "res: secretsdb.delete(del_msg.dn) res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] =", "because rdn_name will handle # it, and it causes problems for modifies anyway", "isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to point at the newly created DC", "provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is None: schema = Schema(domainsid, schemadn=names.schemadn)", "if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s'", "< 1000 or next_rid > 1000000000: error = \"You want to run SAMBA", "\"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid),", "!#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\"", "else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the", "setup setup_add_ldif(samdb, setup_path(\"provision_dns_add.ldif\"), { \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn, \"DNSPASS_B64\": b64encode(dnspass.encode('utf-16-le')), \"HOSTNAME\" : names.hostname,", "'r').read() data = data.lstrip() if data is None or data == \"\": make_smbconf(smbconf,", "Domain name :param hostname: Local hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path,", "None self.configdn = None self.schemadn = None self.ldapmanagerdn = None self.dnsdomain = None", "= \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir = \" + os.path.abspath(targetdir)", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL on the sysvol/<dnsname>/Policies", "logger.info(\"Setting up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn,", "(the password_hash module in particular) need # to know what level of AD", "am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database. :note: This will wipe", "ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start() #", "smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid,", "adminstrators\" group :param domainsid: The SID of the domain :param dnsdomain: The DNS", "root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials,", "to run SAMBA 4 on a domain and forest function level which itself", "\"\"\"Set the ACL for the sysvol share and the subfolders :param samdb: An", "\"\"\"Find a user or group from a list of possibilities. :param nssfn: NSS", "will, for better or worse, default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain =", "\\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf", "NSS Function to try (should raise KeyError if not found) :param names: Names", "None: privdir = os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\")))", "(realm, hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be", "may not be stored locally but in LDAP. \"\"\" assert session_info is not", "serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf file based on a", "global_schema=False, am_rodc=am_rodc) # Set the NTDS settings DN manually - in order to", "domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type ==", "scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx = 0 p = re.compile(r'-')", "registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting", "controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except Exception: samdb.transaction_cancel()", "setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a", "dirs, files in os.walk(sysvol, topdown=False): for name in files: if canchown: os.chown(os.path.join(root, name),", "# This program is free software; you can redistribute it and/or modify #", "the provisioned tree exists and we connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) # And", "dnsdomain.lower()) else: dnsname = None shortname = netbiosname.lower() # We don't need to", "is None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass is None: machinepass = samba.generate_random_password(128,", "% shortname ] if secure_channel_type == SEC_CHAN_BDC and dnsname is not None: #", "if lp is None: lp = samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf)", "the info in the current database. :param paths: paths object :param dnsdomain: DNS", "up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif)", "\"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def", "used to track range of USN modified by provision and upgradeprovision. This value", ":param sysvol: Physical path for the sysvol folder :param gid: The GID of", "\"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return", "ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init()", "realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir,", "one there already if os.path.exists(smbconf): # if Samba Team members can't figure out", "realm.upper() if lp is None: lp = samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf):", "file. The erase parameter controls whether to erase the existing data, which may", "if eadb and not lp.get(\"posix:eadb\"): if targetdir is not None: privdir = os.path.join(targetdir,", "session_info, lp): \"\"\"Setup the privileges database. :param path: Path to the privileges database.", "fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup", "= lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None,", "logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb", "if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def", "the database. :note: This will wipe the Sam Database! :note: This function always", "\"internal\": sid_generator_line = \"\" else: sid_generator_line = \"sid generator = \" + sid_generator", "{ \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up", "controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise #", "\"member server\", \"standalone\") if invocationid is None: invocationid = str(uuid.uuid4()) if not os.path.exists(paths.private_dir):", "netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain", "names.domaindn}) logger.info(\"Adding computers container\") setup_add_ldif(samdb, setup_path(\"provision_computers_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb,", "in the current database. :param paths: paths object :param dnsdomain: DNS Domain name", "\"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\"", "lp=None): \"\"\"Provision samba4 :note: caution, this wipes all existing data! \"\"\" if domainsid", "( netbiosname, sitename, configdn) return names def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir,", "(paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if paths.sysvol is None: logger.info(\"Existing smb.conf", "Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if", "self.hostname = None self.sitename = None self.smbconf = None def update_provision_usn(samdb, low, high,", "a zone file on the first DC, it should be # replicated with", "database, but don's load the global schema and don't connect # quite yet", "KeyError: pass raise KeyError(\"Unable to find user/group in %r\" % names) findnss_uid =", "# but we don't delete the old record that we are about to", "else: raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start() # only install a", "\\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec", "File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\":", "possibilities. :param nssfn: NSS Function to try (should raise KeyError if not found)", "[] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"])", "NTDS settings DN manually - in order to have it already around #", "bind_gid = None if targetdir is not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\")", "sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return names def make_smbconf(smbconf,", "\"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not None: if dnsdomain is", "netbiosname, \"DOMAIN\": domain, \"REALM\": realm, \"SERVERROLE\": serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line,", "import samba.param import samba.registry from samba.schema import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS", "'%s' must not be equal to hostname '%s'!\" % (realm, hostname)) if netbiosname.upper()", "paths.bind_gid = bind_gid if hostip is None: logger.info(\"Looking up IPv4 addresses\") hostips =", "% provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\"", "= \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return names def make_smbconf(smbconf, hostname, domain,", "\"# No LDAP backend\" if provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\"", "SamDB rootdse. :param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn,", "wheel group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID,", "LDB object connect to sam.ldb :param low: The lowest USN modified by this", "names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]):", "scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if", "configuration file. :param path: Path to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path,", "existing data! \"\"\" if domainsid is None: domainsid = security.random_sid() else: domainsid =", "sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" %", "Set the NTDS settings DN manually - in order to have it already", ":return: The biggest USN in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\",", "and/or release manager. They have a big impact on the whole program! domainControllerFunctionality", "policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path,", "privileges database. :param session_info: Session info. :param credentials: Credentials :param lp: Loadparm context", "attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not None:", "{ \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir })", "Session information :param credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\")", "if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You", "Ldb Handle to the secrets database :param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir,", "newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn,", "IPv4 IP :param hostip6: Local IPv6 IP :param hostname: Local hostname :param realm:", "self.sitename = None self.smbconf = None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the", "raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start() # only install a new", "if adminpass is None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass", "LDIF file. :param subst_vars: Dictionary with substitution variables. \"\"\" assert ldb is not", "received a copy of the GNU General Public License # along with this", "p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\")", "None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden chars newnbname =", "\\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl=", ":param nobody_uid: uid of the UNIX nobody user. :param users_gid: gid of the", "name in files: setntacl(lp, os.path.join(root, name), acl, domsid) for name in dirs: setntacl(lp,", "realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm,", "hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove forbidden chars newnbname = \"\"", "setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database. :param path: Path to the privileges", "None: # now display slapd_command_file.txt to show how slapd must be # started", "(ie. DC=...) :param samdb: An LDB object on the SAM db :param lp:", "None if paths.sysvol is None: logger.info(\"Existing smb.conf does not have a [sysvol] share,", "reg.diff_apply(provision_reg) def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database. :param path: path to", "sid_generator = \"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"])", "try: logger.info(\"Setting up the registry\") setup_registry(paths.hklm, session_info, lp=lp) logger.info(\"Setting up the privileges database\")", "ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf,", "else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA):", "LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN in sam.ldb This", "domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match chosen domain '%s'! Please", "high: The highest USN modified by this upgrade :param replace: A boolean indicating", "ACL for GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL,", "= \"\" gc_msdcs_ip6_line = \"\" if hostip is not None: hostip_base_line = \"", "a named.conf file (including GSS-TSIG configuration). :param paths: all paths :param realm: Realm", "\"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\"", "ensure that we don't have more # than one record for this SID,", "(netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname = netbiosname.lower() # We don't need", "is distributed in the hope that it will be useful, # but WITHOUT", "\"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr }) logger.info(\"Setting up display specifiers\")", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public", "upgrade :param high: The highest USN modified by this upgrade\"\"\" tab = []", "database :param machinepass: Machine password \"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\",", "entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = []", "ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\": if paths.netlogon is", "Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) #", "security from samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003,", "names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn,", "logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn,", "samdb.transaction_cancel() raise else: samdb.transaction_commit() def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None,", "ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger,", "names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\":", "smb.conf does not have a [sysvol] share, but you\" \" are configuring a", "# only install a new smb.conf if there isn't one there already if", "is higher than its actual DC function level (2008_R2). This won't work!\") domainFunctionality", "to freeze the zone while we update the contents if targetdir is None:", "policyguid: GUID of the default domain policy :param policyguid_dc: GUID of the default", "to run SAMBA 4 with a next_rid of %u, \" % (next_rid) error", "machinepass = samba.generate_random_password(128, 255) if dnspass is None: dnspass = samba.generate_random_password(128, 255) if", "lp=lp) secrets_ldb.erase() secrets_ldb.load_ldif_file_add(setup_path(\"secrets_init.ldif\")) secrets_ldb = Ldb(path, session_info=session_info, lp=lp) secrets_ldb.transaction_start() try: secrets_ldb.load_ldif_file_add(setup_path(\"secrets.ldif\")) if (backend_credentials", "DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename,", "= \"You want to run SAMBA 4 with a next_rid of %u, \"", "can redistribute it and/or modify # it under the terms of the GNU", "was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"]) samdb.modify_ldif(schema.schema_dn_modify) samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb,", "ProvisioningError(error) # ATTENTION: Do NOT change these default values without discussion with the", "the # team and/or release manager. They have a big impact on the", "version 3 of the License, or # (at your option) any later version.", "ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private dir. :param ldb: LDB file", "this might be determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try: msg =", "SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) # Set the NTDS settings DN manually", "remove the %s file and let provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile))", "\"DOMAINDN\": names.domaindn}) logger.info(\"Modifying computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb", "pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\":", "substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None)", "lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names:", "dnsdomain: DNS domain name of the AD domain :param policyguid: GUID of the", "( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry from samba.schema import", "'%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def setup_secretsdb(paths, session_info, backend_credentials, lp): \"\"\"Setup the", "\"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "of the GNU General Public License # along with this program. If not,", "paths): \"\"\"Write out a dns_update_list file\"\"\" # note that we use no variable", "be added or none (using transactions). :param ldb: LDB file to import into.", "is used to track range of USN modified by provision and upgradeprovision. This", "\"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid): \"\"\"Return", "= samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn,", "Foundation; either version 3 of the License, or # (at your option) any", "session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is None: schema = Schema(domainsid, schemadn=names.schemadn) #", "modules loading - we # just want to wipe and re-initialise the database,", "{ \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname,", "expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError,", "ndr_unpack from samba.provision.backend import ( ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import", "data = open(smbconf, 'r').read() data = data.lstrip() if data is None or data", "than 1000000000 # as the upper range of the rIDAvailablePool is 1073741823 and", "The lowest USN modified by this upgrade :param high: The highest USN modified", "samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name, version, )", "%s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password:", "from a list of possibilities. :param nssfn: NSS Function to try (should raise", "\"\"\"Create a PHP LDAP admin configuration file. :param path: Path to write the", "import data into :param ldif_path: Path of the LDIF file to load :param", "sysvol folder :param dnsdomain: DNS name of the AD domain :param guid: The", "parameter controls whether to erase the existing data, which may not be stored", "must match chosen realm '%s'! Please remove the smb.conf file and let provision", "function level which itself is higher than its actual DC function level (2008_R2).", "domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time() * 1e7)), # seconds", "keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf, { \"DNSDOMAIN\": dnsdomain,", "samba.generate_random_password(12, 32) if krbtgtpass is None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass is", "sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir,", "import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr", "safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type,", "provision or an upgradeprovision :param sam: An LDB object pointing to the sam.ldb", "from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, ) from samba.idmap import IDmapDB from", "= samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert", "Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup the registry. :param", "connect samdb.set_ntds_settings_dn(\"CN=NTDS Settings,%s\" % names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up", "os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line = \"\" if sid_generator", "names def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a", "gid %u\" % ( dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc + \"", ":param secretsdb: Ldb Handle to the secrets database :param machinepass: Machine password \"\"\"", "along with this program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up", "backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info,", "<NAME> <<EMAIL>> 2005 # # This program is free software; you can redistribute", "[\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"] = [str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass]", "= \"%s%c\" % (newnbname, x) #force the length to be <16 netbiosname =", "\"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\":", "context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return", "created when the Schema object was constructed logger.info(\"Setting up sam.ldb schema\") samdb.add_ldif(schema.schema_dn_add, controls=[\"relax:0\"])", "msg[\"flatname\"] here, because rdn_name will handle # it, and it causes problems for", "Path of the new named.conf file. :param dnsdomain: DNS Domain name :param hostname:", ":return: Value return by first names list. \"\"\" for name in names: try:", "# Set the NTDS settings DN manually - in order to have it", "\"%s%c\" % (newnbname, x) # force the length to be <16 netbiosname =", "= lp.get(\"server role\") assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if invocationid", "in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\")", "self.idmapdb = None self.secrets = None self.keytab = None self.dns_keytab = None self.dns", "os.path.exists(paths.secrets): os.unlink(paths.secrets) keytab_path = os.path.join(paths.private_dir, paths.keytab) if os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab)", ":param low: The lowest USN modified by this upgrade :param high: The highest", "assert ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel()", "error.\"\"\" def __init__(self, value): self.value = value def __str__(self): return \"ProvisioningError: \" +", "or next_rid > 1000000000: error = \"You want to run SAMBA 4 with", "the length to be <16 netbiosname = newnbname[0:15] else: netbiosname = hostname.upper() if", "except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed to chown %s to bind gid %u\",", "import samba.registry from samba.schema import Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS = \"", "Handle to the secrets database :param machinepass: Machine password \"\"\" attrs = [\"whenChanged\",", "pointing to the sam.ldb :return: an integer corresponding to the highest USN modified", "none (using transactions). :param ldb: LDB file to import into. :param ldif_path: Path", "if sid_generator is None: sid_generator = \"internal\" assert domain is not None domain", "}) logger.info(\"Setting up display specifiers\") display_specifiers_ldif = read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\":", "lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf = lp.configfile return paths def guess_names(lp=None,", "This function always removes the local SAM LDB file. The erase parameter controls", "private directory :param keytab_name: File name of DNS keytab file \"\"\" setup_file(setup_path(\"named.conf\"), paths.namedconf,", "}) def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid):", "\"generated at %s\", paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup()", "\"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr", "try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain,", "group. \"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid)", "+ \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp,", "write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths,", "file (including GSS-TSIG configuration). :param path: Path of the new named.conf file. :param", "ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be that this attribute does not exist in this", "%s file and let provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn", "is None: os.system(rndc + \" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths):", "None: raise ProvisioningError(\"guess_names: 'server role' not specified in supplied %s!\" % lp.configfile) serverrole", "= None self.sitename = None self.smbconf = None def update_provision_usn(samdb, low, high, replace=False):", "= [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not None: if", "to update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb,", "Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\", expression=\"\", scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except", "the rIDAvailablePool is 1073741823 and # we don't want to create a domain", "object \"\"\" # Set ACL for GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain,", ":param session_info: Session information :param credentials: Credentials :param lp: Loadparm context \"\"\" reg", "sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid,", "ldb in the private dir. :param ldb: LDB file to import data into", "names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"FOREST_FUNCTIONALITY\": str(forestFunctionality), \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SITES_DESCRIPTOR\": descr", "names=names, logger=logger) elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names,", "ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set", "the sysvol/<dnsname>/Policies folder and the policy folders beneath. :param sysvol: Physical path for", "ProvisionPaths() paths.private_dir = lp.get(\"private dir\") # This is stored without path prefix for", "return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts and other important objects #", "lp.get(\"realm\") if dnsdomain is None or dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not", "{\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit()", "\"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s'", "str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb,", "\"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\"", "Path to the sysvol folder :param dnsdomain: DNS name of the AD domain", "= os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"],", "it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None: domaindn = \"DC=\" +", "descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\":", "here, because rdn_name will handle # it, and it causes problems for modifies", "b64encode(krbtgtpass.encode('utf-16-le')) }) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid,", "named.conf file (including GSS-TSIG configuration). :param paths: all paths :param realm: Realm name", "(default) \"\"\" tab = [] if not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE,", "= ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid))", "not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin DN: %s\" %", "Realm '%s' must not be equal to netbios hostname '%s'!\" % (realm, netbiosname))", "the sysvol folder :param gid: The GID of the \"Domain adminstrators\" group :param", "}) logger.info(\"Setting up self join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid,", "= schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain names.domain = domain", "data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename,", "a file containing zone statements suitable for inclusion in a named.conf file (including", "are described at # \"How Core Group Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid", "domainsid is None: domainsid = security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt the", "hostip6=None, domainsid=None, next_rid=1000, adminpass=None, ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None,", "bind gid %u\" % ( dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc +", "smbconfsuffix = \"standalone\" if sid_generator is None: sid_generator = \"internal\" assert domain is", "[\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not None: if dnsdomain", "the database via the database # modifictions below, but we need them set", "default # this ensures that any smb.conf parameters that were set # on", "path for the sysvol folder :param dnsdomain: DNS domain name of the AD", "and dnsname is not None: # we are a domain controller then we", "\"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers container\")", "[\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname, realm.upper())] msg[\"msDS-KeyVersionNumber\"]", "\"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)}) setup_add_ldif(samdb, setup_path(\"provision_group_policy.ldif\"), { \"POLICYGUID\": policyguid, \"POLICYGUID_DC\":", "netbiosname = lp.get(\"netbios name\") if netbiosname is None: netbiosname = hostname # remove", "OSError: pass samdb = Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP", "seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn,", "serverrole, lp.configfile)) if serverrole == \"domain controller\": if domain is None: # This", "names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up sam.ldb users and groups\")", "if len(samdb.search(\"(cn=Administrator)\")) != 1: raise ProvisioningError(\"No administrator account found\") def findnss(nssfn, names): \"\"\"Find", "schema raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab,", "original in EJS: # Copyright (C) <NAME> <<EMAIL>> 2005 # # This program", "lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must match chosen domain", "\"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\"", "is None or data == \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator,", "provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None,", "and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger, session_info, credentials,", "ExistingBackend, FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry from samba.schema import Schema", "res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl =", "Realm '%s' must not be equal to hostname '%s'!\" % (realm, hostname)) if", "hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain,", "%s\" % names.domaindn) # impersonate domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if", "might be that this attribute does not exist in this schema raise if", "samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE) provision_reg = setup_path(\"provision.reg\") assert os.path.exists(provision_reg)", "domainguid else: domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn,", "subst_vars: Optional dictionary with substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls)", "\\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\", "SID: %s\" % str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" % adminpass)", "serverrole == \"domain controller\": # Set up group policies (domain policy and domain", "def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>,", "(lp.get(\"realm\").upper(), realm, lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in", "descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\":", "\" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE =", "provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is None: domaindn =", "realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None,", "backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else:", "(names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\":", "os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list = os.path.join(paths.private_dir, \"dns_update_list\") paths.spn_update_list = os.path.join(paths.private_dir, \"spn_update_list\")", "Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: # now display slapd_command_file.txt", "\"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\", "= None self.lp = None self.samdb = None def check_install(lp, session_info, credentials): \"\"\"Check", "None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None: smbconf = samba.param.default_path()", "4 has been \" \"generated at %s\", paths.krb5conf) if serverrole == \"domain controller\":", ":param paths: paths object :param dnsdomain: DNS Domain name :param domaindn: DN of", "License # along with this program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for", ":param ldif_path: Path to the LDIF file. :param subst_vars: Dictionary with substitution variables.", "DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid)", "self.domaindn = None self.lp = None self.samdb = None def check_install(lp, session_info, credentials):", "keytab code to update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg)", "\" unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list", "None self.dnsdomain = None self.realm = None self.netbiosname = None self.domain = None", "if schemadn is None: schemadn = \"CN=Schema,\" + configdn if sitename is None:", "lp.configfile)) if domaindn is None: domaindn = \"DC=\" + dnsdomain.replace(\".\", \",DC=\") if domain", "naming contexts and other important objects # \"get_schema_descriptor\" is located in \"schema.py\" def", ":param idmap: IDmap db object. :param sid: The domain sid. :param domaindn: The", "os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO for a", "None: logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP Admin User: %s\"", "get_last_provision_usn(sam): \"\"\"Get the lastest USN modified by a provision or an upgradeprovision :param", "the netlogon folder :param sysvol: Physical path for the sysvol folder :param gid:", "dnsdomain, domaindn, lp): \"\"\"Set the ACL for the sysvol share and the subfolders", "= \"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock dir =", "\"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid)", "samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm, dnsdomain, private_dir): \"\"\"Write", "This is partially Samba4 specific and should be replaced by the correct #", "if ldapadminpass is None: # Make a new, random password between Samba and", "further documentation required for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN", "if lp is None: lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain,", "session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the partitions for the SAM database.", "ldif_path: LDIF file path. :param subst_vars: Optional dictionary with substitution variables. \"\"\" data", "{ \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid,", "controller\", \"member server\", \"standalone\") if invocationid is None: invocationid = str(uuid.uuid4()) if not", "\" + hostip gc_msdcs_ip_line = \"gc._msdcs IN A \" + hostip else: hostip_base_line", "private dir. :param ldb: LDB object. :param ldif_path: LDIF file path. :param subst_vars:", "now display slapd_command_file.txt to show how slapd must be # started next time", "substitute_var, valid_netbios_name, version, ) from samba.dcerpc import security from samba.dcerpc.misc import ( SEC_CHAN_BDC,", "file \"\"\" setup_file(setup_path(\"named.txt\"), path, { \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir,", "\"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid", "all existing data! \"\"\" if domainsid is None: domainsid = security.random_sid() else: domainsid", "want to run SAMBA 4 on a domain and forest function level which", "samba.dcerpc.misc import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES,", "the schema won't be loaded from the # DB samdb.connect(path) if fill ==", "= os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm = \"hklm.ldb\" paths.hkcr = \"hkcr.ldb\"", "hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False, lp=None): \"\"\"Create a new smb.conf file", "names.dnsdomain) paths.bind_gid = bind_gid if hostip is None: logger.info(\"Looking up IPv4 addresses\") hostips", "Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn,", "attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta =", "= None self.hostname = None self.sitename = None self.smbconf = None def update_provision_usn(samdb,", "domain_sid) return ndr_pack(sec) class ProvisionPaths(object): def __init__(self): self.shareconf = None self.hklm = None", "smbconf is not None if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname =", "res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol, dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)),", "paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon = lp.get(\"path\", \"netlogon\") paths.smbconf =", "know what level of AD we are emulating. # These will be fixed", "addresses\") hostips = samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No external IPv4 address", "return paths def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None,", "controller then we add servicePrincipalName # entries for the keytab code to update.", "findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None if targetdir is not None: smbconf", "setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line,", "\"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID based", "is not None domain = domain.upper() assert realm is not None realm =", "if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"] =", "by provision and upgradeprovision. This value is used afterward by next provision to", "to the policy folder \"\"\" if guid[0] != \"{\": guid = \"{%s}\" %", "\"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc,", "Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions", "by next provision to figure out if the field have been modified since", "hostips = samba.interface_ips(lp, False) if len(hostips) == 0: logger.warning(\"No external IPv4 address has", "to figure out if the field have been modified since last provision. :param", "sysvolpath: Physical path for the sysvol folder :param dnsdomain: DNS domain name of", "\"\"\"Setup the idmap database. :param path: path to the idmap database :param session_info:", "= samba.generate_random_password(128, 255) if dnspass is None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass", "1000) raise ProvisioningError(error) # ATTENTION: Do NOT change these default values without discussion", "\\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;DA)\" \\ \"(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPRC;;;RU)\" \\ \"(A;CI;LC;;;RU)\" \\", "session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\" if provision_backend.type is not", "\"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\ \"(OU;CIIOSA;CR;;f0f8ffab-1191-11d0-a060-00aa006c33ed;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec =", "self.private_dir = None class ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn = None", "samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except Exception:", "None self.realm = None self.netbiosname = None self.domain = None self.hostname = None", "1000000000 # as the upper range of the rIDAvailablePool is 1073741823 and #", "samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"),", "should be # replicated with DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip,", "been \" \"generated at %s\", paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp, logger,", "The DN of the domain (ie. DC=...) :param samdb: An LDB object on", "= p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx + 1 return range else: return", "are the default # this ensures that any smb.conf parameters that were set", "are installed, your Samba4 server will be ready to use\") logger.info(\"Server Role: %s\"", "\"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True)", "credentials): \"\"\"Check whether the current install seems ok. :param lp: Loadparm context :param", "ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type selected\") provision_backend.init() provision_backend.start()", "if next_rid < 1000 or next_rid > 1000000000: error = \"You want to", "by first names list. \"\"\" for name in names: try: return nssfn(name) except", "private_dir, keytab_name): \"\"\"Write out a file containing zone statements suitable for inclusion in", "last provision. :param samdb: An LDB object connect to sam.ldb :param low: The", "logger.info(\"Existing smb.conf does not have a [sysvol] share, but you\" \" are configuring", "\"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb,", "\"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir, \"dns\", dnsdomain + \".zone\") paths.dns_update_list", "\"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\":", "= None self.dnsdomain = None self.realm = None self.netbiosname = None self.domain =", "ldb.Dn(schema.ldb, names.configdn).get_casefold(), \"DOMAINDN\": ldb.Dn(schema.ldb, names.domaindn).get_casefold(), \"LDAP_BACKEND_LINE\": ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type,", "The domain DN. :param root_uid: uid of the UNIX root user. :param nobody_uid:", ":param path: path to the idmap database :param session_info: Session information :param credentials:", "samba.generate_random_password(128, 255) if dnspass is None: dnspass = samba.generate_random_password(128, 255) if ldapadminpass is", "samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb,", "str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CREATTIME\": str(int(time.time()", "= [\"top\", \"primaryDomain\"] if dnsname is not None: msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"]", "is partially Samba4 specific and should be replaced by the correct # DNS", "= b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration.ldif\"), { \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain,", "on purpose, it's up to the caller to do this job. :param path:", "\"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\":", "substitution on this file # the substitution is done at runtime by samba_dnsupdate", "in the provision\"\"\" res = samdb.search(expression=\"objectClass=*\",base=basedn, scope=ldb.SCOPE_SUBTREE,attrs=[\"uSNChanged\"], controls=[\"search_options:1:2\", \"server_sort:1:1:uSNChanged\", \"paged_results:1:1\"]) return res[0][\"uSNChanged\"] def", "provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn result.paths = paths result.lp = lp", "= hostips[0] if len(hostips) > 1: logger.warning(\"More than one IPv4 address found. Using", "sitename, configdn) return names def make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator=\"internal\", eadb=False,", "# it, and it causes problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary", "sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks", "\" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list file\"\"\" #", "PARTICULAR PURPOSE. See the # GNU General Public License for more details. #", "dnsdomain, str(policy[\"cn\"])) set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid,", "system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname,", "\\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\", "highest USN modified by (upgrade)provision, 0 is this value is unknown \"\"\" entry", "because that would delete the keytab and previous password. res = secretsdb.search(base=\"cn=Primary Domains\",", "self.dns_keytab = None self.dns = None self.winsdb = None self.private_dir = None class", "to erase the existing data, which may not be stored locally but in", "your Samba4 server will be ready to use\") logger.info(\"Server Role: %s\" % serverrole)", "the contents if targetdir is None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc +", "sid_generator = \"internal\" assert domain is not None domain = domain.upper() assert realm", "> domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA 4 on a domain and", "os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def setup_registry(path, session_info, lp): \"\"\"Setup", "dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc + \" unfreeze \" + lp.get(\"realm\"))", "0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p,", "policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp,", "names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn,", "= \"sid generator = \" + sid_generator sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon", "ldif_path: Path of the LDIF file to load :param subst_vars: Optional variables to", "for el in msg: if el != 'dn': msg[el].set_flags(ldb.FLAG_MOD_REPLACE) secretsdb.modify(msg) secretsdb.rename(res[0].dn, msg.dn) else:", "slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri) else: raise ValueError(\"Unknown LDAP backend type selected\")", "useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #", "function level (2008_R2). This won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level #", "delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn): \"\"\" This function return the", "(first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files in os.walk(sysvol, topdown=False): for", "Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp) def provision(logger,", "{ \"CONFIGDN\": names.configdn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"DNSDOMAIN\": names.dnsdomain, \"DOMAIN\": names.domain, \"SCHEMADN\": names.schemadn,", "an empty smb.conf gives, then we need to be smarter. # Pretend it", "\" IN AAAA \" + hostip6 hostip6_host_line = hostname + \" IN AAAA", "= None self.private_dir = None class ProvisionNames(object): def __init__(self): self.rootdn = None self.domaindn", "new smb.conf if there isn't one there already if os.path.exists(smbconf): # if Samba", "= \"restructuredText\" from base64 import b64encode import os import re import pwd import", "domainControllerFunctionality: raise ProvisioningError(\"You want to run SAMBA 4 on a domain and forest", "set_provision_usn(samdb, 0, maxUSN) create_krb5_conf(paths.krb5conf, dnsdomain=names.dnsdomain, hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba", "None self.winsdb = None self.private_dir = None class ProvisionNames(object): def __init__(self): self.rootdn =", "{ \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill == FILL_FULL: logger.info(\"Setting up sam.ldb users", ":note: This function does not handle exceptions and transaction on purpose, it's up", "previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))),", "DB # In future, this might be determined from some configuration kerberos_enctypes =", "dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 if dom_for_fun_level > domainControllerFunctionality: raise ProvisioningError(\"You want", "hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if hostip6 is not None: hostip6_base_line", "in \"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\"", "= setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill,", "paths.sysvol is not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL:", "without discussion with the # team and/or release manager. They have a big", "\"\"\"Setup the registry. :param path: Path to the registry database :param session_info: Session", "in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) # force the length to", "None: privatedir_line = \"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\")) lockdir_line = \"lock", "the complete path to the policy folder \"\"\" if guid[0] != \"{\": guid", "open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775)", "\\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def", "to a secrets database. :param secretsdb: Ldb Handle to the secrets database :param", "(domain, netbiosname)) else: domain = netbiosname if domaindn is None: domaindn = \"DC=\"", "str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type is", "idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param samdb: Sam", "msg[\"objectClass\"] = [\"top\", \"primaryDomain\", \"kerberosSecret\"] msg[\"realm\"] = [realm] msg[\"saltPrincipal\"] = [\"host/%s@%s\" % (dnsname,", "error += \"the valid range is %u-%u. The default is %u.\" % (", "nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this wipes all existing", "UNIX nobody user. :param users_gid: gid of the UNIX users group. :param wheel_gid:", "%s must match chosen realm '%s'! Please remove the smb.conf file and let", "object pointing to the sam.ldb :return: an integer corresponding to the highest USN", "setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in the private dir. :param ldb: LDB", "def secretsdb_self_join(secretsdb, domain, netbiosname, machinepass, domainsid=None, realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain", "match chosen domain '%s'! Please remove the %s file and let provision generate", "folder :param dnsdomain: DNS domain name of the AD domain :param policyguid: GUID", "dnsdomain, \"Policies\", guid) return policy_path def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path,", "Now set up the right msDS-SupportedEncryptionTypes into the DB # In future, this", "In future, this might be determined from some configuration kerberos_enctypes = str(ENC_ALL_TYPES) try:", "GSS-TSIG configuration). :param path: Path of the new named.conf file. :param dnsdomain: DNS", "names.domaindn}) # add the NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn", "None: # we are a domain controller then we add servicePrincipalName # entries", "names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(), names.dnsdomain.lower()) }) def getpolicypath(sysvolpath, dnsdomain, guid):", "\"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID based SPNs ntds_dn = \"CN=NTDS", "credentials: Credentials :param lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path,", "\"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path,", "with the # team and/or release manager. They have a big impact on", "keytab_name): \"\"\"Write out a file containing zone statements suitable for inclusion in a", "read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from samba.ndr import ndr_pack, ndr_unpack from samba.provision.backend", "try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration data\") descr = b64encode(get_sites_descriptor(domainsid)) setup_add_ldif(samdb,", "complete path to the policy folder \"\"\" if guid[0] != \"{\": guid =", "\"privateKeytab\"] if realm is not None: if dnsdomain is None: dnsdomain = realm.lower()", "DomainDN: %s\" % names.domaindn) # impersonate domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info)", "paths.krb5conf) if serverrole == \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url)", "seems ok. :param lp: Loadparm context :param session_info: Session information :param credentials: Credentials", "provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel() raise # Now commit the secrets.ldb", "is None: rootdn = domaindn if configdn is None: configdn = \"CN=Configuration,\" +", "None or data == \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb,", "Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: # now display", "in a named.conf file (including GSS-TSIG configuration). :param paths: all paths :param realm:", "be None for no controls \"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars)", "= domaindn if configdn is None: configdn = \"CN=Configuration,\" + rootdn if schemadn", "return ndr_pack(sec) def get_domain_descriptor(domain_sid): sddl= \"O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;5f202010-79a5-11d0-9020-00c04fc2d4cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\", "database. :param path: path to the idmap database :param session_info: Session information :param", "files: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for", "targetdir is not None: smbconf = os.path.join(targetdir, \"etc\", \"smb.conf\") elif smbconf is None:", "record for this SID, realm or netbios domain at a time, # but", "a host to its own domain.\"\"\" assert isinstance(invocationid, str) if ntdsguid is not", "samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn), attrs=[\"cn\", \"nTSecurityDescriptor\"], expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl()", "data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb", "names.netbiosname = netbiosname names.hostname = hostname names.sitename = sitename names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" %", "to bind gid %u\" % ( dns_dir, paths.bind_gid)) if targetdir is None: os.system(rndc", "USN modified by this upgrade :param high: The highest USN modified by this", "paths object :param dnsdomain: DNS Domain name :param domaindn: DN of the Domain", "(realm, domain)) if rootdn is None: rootdn = domaindn if configdn is None:", "controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass) domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert", "local SAM LDB file. The erase parameter controls whether to erase the existing", "+ 1 return range else: return None class ProvisionResult(object): def __init__(self): self.paths =", "= None self.samdb = None self.idmapdb = None self.secrets = None self.keytab =", ":param sysvolpath: Path to the sysvol folder :param dnsdomain: DNS name of the", "create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6, hostname, realm, domainguid, ntdsguid): \"\"\"Write out", "* 1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn, \"NETBIOSNAME\": names.netbiosname, \"DEFAULTSITE\": names.sitename, \"CONFIGDN\":", "session_info=session_info, lp=lp) logger.info(\"Setting up SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names,", "setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb,", "== \"internal\": sid_generator_line = \"\" else: sid_generator_line = \"sid generator = \" +", "level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files in os.walk(sysvol, topdown=False): for name", "\\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) class", "a DC.\") logger.info(\"Please either remove %s or see the template at %s\" %", "assert realm is not None realm = realm.upper() if lp is None: lp", "larger than 1000000000 # as the upper range of the rIDAvailablePool is 1073741823", "paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir,", "a new shares config db if there is none if not os.path.exists(paths.shareconf): logger.info(\"Setting", "\"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain,", "function return the biggest USN present in the provision :param samdb: A LDB", "rootdn is None: rootdn = domaindn if configdn is None: configdn = \"CN=Configuration,\"", "Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\":", "specified in supplied %s!\", lp.configfile) dnsdomain = dnsdomain.lower() if serverrole is None: serverrole", "\"NT4SYNC\" FILL_DRS = \"DRS\" SYSVOL_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)\" POLICIES_ACL = \"O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)\" def set_dir_acl(path, acl,", "\"LDAPADMINREALM\": backend_credentials.get_realm(), \"LDAPADMINPASS_B64\": b64encode(backend_credentials.get_password()) }) return secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path,", "samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn,", "raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for provisioning. :param", "= newnbname[0:15] assert netbiosname is not None netbiosname = netbiosname.upper() if not valid_netbios_name(netbiosname):", "or none (using transactions). :param ldb: LDB file to import into. :param ldif_path:", "Public License for more details. # # You should have received a copy", "open(smbconf, 'r').read() data = data.lstrip() if data is None or data == \"\":", "netbiosname: raise ProvisioningError(\"guess_names: Domain '%s' must not be equal to short host name", "in supplied %s!\" % lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\")", "1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do NOT change these default values without", "make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain,", "setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is None: schema", "of the default domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path) policy_path =", "Optional dictionary with substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def", "Team members can't figure out the weird errors # loading an empty smb.conf", "match chosen server role '%s'! Please remove the smb.conf file and let provision", "be loaded from the # DB samdb.connect(path) if fill == FILL_DRS: return samdb", "is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password()) }) else: setup_add_ldif(secrets_ldb,", "dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database. :note:", "= os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir", "also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir) result = ProvisionResult() result.domaindn = domaindn result.paths =", "self.hkpt = None self.samdb = None self.idmapdb = None self.secrets = None self.keytab", "uid of the UNIX nobody user. :param users_gid: gid of the UNIX users", "schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger)", "to the idmap database :param session_info: Session information :param credentials: Credentials :param lp:", "a [netlogon] share, but you are configuring a DC.\") logger.info(\"Please either remove %s", "\"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\"", "None: machinepass = samba.generate_random_password(128, 255) if dnspass is None: dnspass = samba.generate_random_password(128, 255)", "\"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema, serverrole, erase=False):", "don't need to set msg[\"flatname\"] here, because rdn_name will handle # it, and", "backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema,", "umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to chown", "<<EMAIL>> 2005 # # This program is free software; you can redistribute it", "'realm=%s' in %s must match chosen realm '%s'! Please remove the smb.conf file", "\"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\"", "without any values that are the default # this ensures that any smb.conf", "sysvol folder :param gid: The GID of the \"Domain adminstrators\" group :param domainsid:", "samdb: An LDB object on the SAM db :param netlogon: Physical path for", "basedn: A string containing the base DN of the provision (ie. DC=foo, DC=bar)", "controls whether to erase the existing data, which may not be stored locally", "paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls,", "rootdn = domaindn if configdn is None: configdn = \"CN=Configuration,\" + rootdn if", "can be None for no controls \"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path,", "at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) def create_named_conf(paths, realm,", "path. :param subst_vars: Optional dictionary with substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars)", "The LDIF here was created when the Schema object was constructed logger.info(\"Setting up", "smb.conf gives, then we need to be smarter. # Pretend it just didn't", "for the \"privateKeytab\" attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\"", "that we use no variable substitution on this file # the substitution is", "isinstance(domainguid, str) if hostip6 is not None: hostip6_base_line = \" IN AAAA \"", "controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP", "if configdn is None: configdn = \"CN=Configuration,\" + rootdn if schemadn is None:", "= domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup '%s' in smb.conf must", "setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database. :param path: path to the idmap", "path for the sysvol folder :param gid: The GID of the \"Domain adminstrators\"", "into :param ldif_path: Path of the LDIF file to load :param subst_vars: Optional", "range else: return None class ProvisionResult(object): def __init__(self): self.paths = None self.domaindn =", "import ( SEC_CHAN_BDC, SEC_CHAN_WKSTA, ) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008_R2, ENC_ALL_TYPES, )", "dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\" : '%s.%s' % ( names.netbiosname.lower(),", "is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start() try: logger.info(\"Setting up", "\"\"\"Update the field provisionUSN in sam.ldb This field is used to track range", "# we are a domain controller then we add servicePrincipalName # entries for", "\"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version }) logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"),", "or x in VALID_NETBIOS_CHARS: newnbname = \"%s%c\" % (newnbname, x) #force the length", "about to modify, # because that would delete the keytab and previous password.", "names=names, serverrole=serverrole, schema=schema) if schema is None: schema = Schema(domainsid, schemadn=names.schemadn) # Load", "domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None,", "or data == \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp)", "if samdb_fill == FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type is not", "the sysvol folder :param dnsdomain: DNS name of the AD domain :param guid:", "= ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\")", "add the NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid =", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "data == \"\": make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) else:", "to short domain name '%s'!\" % (realm, domain)) if rootdn is None: rootdn", "idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid)", "we are emulating. # These will be fixed into the database via the", "names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the private", "def __init__(self): self.paths = None self.domaindn = None self.lp = None self.samdb =", "\"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "= lp result.samdb = samdb return result def provision_become_dc(smbconf=None, targetdir=None, realm=None, rootdn=None, domaindn=None,", "\"\"\" assert session_info is not None # We use options=[\"modules:\"] to stop the", "hostip6_base_line = \" IN AAAA \" + hostip6 hostip6_host_line = hostname + \"", "beneath. :param sysvol: Physical path for the sysvol folder :param dnsdomain: The DNS", "OSError: pass os.mkdir(dns_dir, 0775) # we need to freeze the zone while we", "{ \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users container\") setup_modify_ldif(samdb, setup_path(\"provision_users_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Adding computers", "SYSVOL_ACL, str(domainsid)) for name in dirs: if canchown: os.chown(os.path.join(root, name), -1, gid) setntacl(lp,", "dnsdomain.lower() if serverrole is None: serverrole = lp.get(\"server role\") if serverrole is None:", "just didn't exist --abartlet data = open(smbconf, 'r').read() data = data.lstrip() if data", "topdown=False): for name in files: setntacl(lp, os.path.join(root, name), acl, domsid) for name in", "% (realm, hostname)) if netbiosname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not", "to the DB - the schema won't be loaded from the # DB", "the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if dom_for_fun_level is None: dom_for_fun_level = DS_DOMAIN_FUNCTION_2003", "than one IPv4 address found. Using %s.\", hostip) if serverrole is None: serverrole", "stop the modules loading - we # just want to wipe and re-initialise", "erase the existing data, which may not be stored locally but in LDAP.", "lp=lp, provision_backend=provision_backend, session_info=session_info, names=names, serverrole=serverrole, schema=schema) if schema is None: schema = Schema(domainsid,", "# \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb", "sysvol = os.path.join(lp.get(\"lock dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix),", "sysvol folder :param dnsdomain: DNS domain name of the AD domain :param policyguid:", "None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn names.domaindn = domaindn names.configdn =", "lp: Loadparm context :return: LDB handle for the created secrets database \"\"\" if", "domaindn, root_uid, nobody_uid, users_gid, wheel_gid): \"\"\"setup reasonable name mappings for sam names to", "ldif_path: Path to the LDIF file. :param subst_vars: Dictionary with substitution variables. \"\"\"", "= \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE", "force the length to be <16 netbiosname = newnbname[0:15] assert netbiosname is not", "targetdir is not None: privatedir_line = \"private dir = \" + os.path.abspath(os.path.join(targetdir, \"private\"))", "be <16 netbiosname = newnbname[0:15] else: netbiosname = hostname.upper() if serverrole is None:", "if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen realm", "for name in files: setntacl(lp, os.path.join(root, name), acl, domsid) for name in dirs:", "True # Set the SYSVOL_ACL on the sysvol folder and subfolder (first level)", "subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid)) for root, dirs, files in os.walk(sysvol, topdown=False):", "A PARTICULAR PURPOSE. See the # GNU General Public License for more details.", "with this program. If not, see <http://www.gnu.org/licenses/>. # \"\"\"Functions for setting up a", "privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None: privatedir_line", "%s\" % names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid))", "new smb.conf file based on a couple of basic settings. \"\"\" assert smbconf", "os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf if there isn't one there", "=' was not specified in supplied %s. Please remove the smb.conf file and", "None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.info(\"Failed", "not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'):", "the Free Software Foundation; either version 3 of the License, or # (at", "option) any later version. # # This program is distributed in the hope", "valid range is %u-%u. The default is %u.\" % ( 1000, 1000000000, 1000)", "into a LDB handle, optionally substituting variables. :note: Either all LDIF data will", "= provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn,", "if serverrole == \"domain controller\": # Set up group policies (domain policy and", "secure_channel_type == SEC_CHAN_BDC and dnsname is not None: # we are a domain", "= os.path.join(policy_path, \"MACHINE\") if not os.path.exists(p): os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if", "lp=lp) if lp is None: lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname,", "machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to", "policyguid_dc: GUID of the default domain controler policy \"\"\" policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid) create_gpo_struct(policy_path)", "is None: rndc = ' '.join(lp.get(\"rndc command\")) os.system(rndc + \" freeze \" +", "255) if backend_type is None: backend_type = \"ldb\" sid_generator = \"internal\" if backend_type", "= realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname", "str(domainsid)) # Set acls on Policy folder and policies folders set_gpos_acl(sysvol, dnsdomain, domainsid,", "Domains\" % domain)) msg[\"secureChannelType\"] = [str(secure_channel_type)] msg[\"objectClass\"] = [\"top\", \"primaryDomain\"] if dnsname is", "only install a new shares config db if there is none if not", "names: try: return nssfn(name) except KeyError: pass raise KeyError(\"Unable to find user/group in", "unfreeze \" + lp.get(\"realm\")) def create_dns_update_list(lp, logger, paths): \"\"\"Write out a dns_update_list file\"\"\"", "hostname=None, domain=None, dnsdomain=None, serverrole=None, rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, sitename=None): \"\"\"Guess configuration settings", "hostname=names.hostname, realm=names.realm) logger.info(\"A Kerberos configuration suitable for Samba 4 has been \" \"generated", "named.conf file (including GSS-TSIG configuration). :param path: Path of the new named.conf file.", "def setup_idmapdb(path, session_info, lp): \"\"\"Setup the idmap database. :param path: path to the", "privatedir_line = \"\" lockdir_line = \"\" if sid_generator == \"internal\": sid_generator_line = \"\"", "ldap_backend_line, }) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb", "domain functionality levels onto the database. # Various module (the password_hash module in", "domainguid = samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make a zone file", "generic provision error.\"\"\" def __init__(self, value): self.value = value def __str__(self): return \"ProvisioningError:", "setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname, \"DNSNAME\"", "first DC, it should be # replicated with DNS replication create_zone_file(lp, logger, paths,", "server # Copyright (C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009", "\" + hostip else: hostip_base_line = \"\" hostip_host_line = \"\" gc_msdcs_ip_line = \"\"", "dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger =", "{ \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF here was created when", "smb.conf must match chosen domain '%s'! Please remove the %s file and let", "%s.\", hostip) if serverrole is None: serverrole = lp.get(\"server role\") assert serverrole in", "transaction on purpose, it's up to the caller to do this job. :param", "members can't figure out the weird errors # loading an empty smb.conf gives,", "provision_backend.start() # only install a new shares config db if there is none", "of the domain (ie. DC=...) :param samdb: An LDB object on the SAM", "= findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid = findnss_gid([users or", "netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal", "KeyError(\"Unable to find user/group in %r\" % names) findnss_uid = lambda names: findnss(pwd.getpwnam,", "if os.path.exists(smbconf): # if Samba Team members can't figure out the weird errors", "\"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri}) def create_zone_file(lp, logger, paths, targetdir, dnsdomain, hostip, hostip6,", "the one we computed earlier samdb.set_schema(schema) # Set the NTDS settings DN manually", "= b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr, \"DOMAINGUID\": domainguid_line", "it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain controller\": if domain", "= os.path.join(paths.private_dir, \"krb5.conf\") paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig =", "domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except OSError: canchown = False", "USN modified by (upgrade)provision, 0 is this value is unknown \"\"\" entry =", "\"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\": version, \"NTDSGUID\": ntdsguid_line, \"DOMAIN_CONTROLLER_FUNCTIONALITY\": str( domainControllerFunctionality)})", "ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend =", ":note: This will wipe the Sam Database! :note: This function always removes the", "= read_ms_ldif( setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt')) display_specifiers_ldif = substitute_var(display_specifiers_ldif, {\"CONFIGDN\": names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\")", "list of controls, can be None for no controls \"\"\" assert isinstance(ldif_path, str)", "dnspass): \"\"\"Add DNS specific bits to a secrets database. :param secretsdb: Ldb Handle", "must match chosen server role '%s'! Please remove the smb.conf file and let", "lp): \"\"\"Setup the idmap database. :param path: path to the idmap database :param", "up sam.ldb rootDSE marking as synchronized\") setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname,", "lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line = \"\" if sid_generator ==", "serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s must match chosen server role '%s'!", "General Public License for more details. # # You should have received a", "# replicated with DNS replication create_zone_file(lp, logger, paths, targetdir, dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6, hostname=names.hostname,", "= lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb,", "None if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper() # remove", "located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files are installed, your", "name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp): \"\"\"Set ACL on", "\"\"\"setup reasonable name mappings for sam names to unix names. :param samdb: SamDB", "= \"internal\" assert domain is not None domain = domain.upper() assert realm is", "registry. :param path: Path to the registry database :param session_info: Session information :param", "[ 'HOST/%s' % shortname ] if secure_channel_type == SEC_CHAN_BDC and dnsname is not", "b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF here", "domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp is None: lp =", "are set in the resulting smb.conf f = open(smbconf, mode='w') lp.dump(f, False) f.close()", "configuration). :param paths: all paths :param realm: Realm name :param dnsdomain: DNS Domain", "hostip_host_line = \"\" gc_msdcs_ip_line = \"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except", "lambda names: findnss(grp.getgrnam, names)[2] def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Setup a ldb in the", "elif serverrole == \"member server\": smbconfsuffix = \"member\" elif serverrole == \"standalone\": smbconfsuffix", "def create_gpo_struct(policy_path): if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p =", "str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP LDAP admin configuration file.", "except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\":", "scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL", "on the SAM db :param netlogon: Physical path for the netlogon folder :param", "Set up group policies (domain policy and domain controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain,", "= samdb.searchone(basedn=domaindn, attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make a zone file on", "next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its own domain.\"\"\"", "not os.path.exists(paths.shareconf): logger.info(\"Setting up share.ldb\") share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up", "\"schema.py\" def get_sites_descriptor(domain_sid): sddl = \"D:(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCLCLORCWOWDSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(AU;CISA;CCDCSDDT;;;WD)\" \\", "and backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\":", "Policy Works\" # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid =", "computers container\") setup_modify_ldif(samdb, setup_path(\"provision_computers_modify.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Setting up sam.ldb data\") setup_add_ldif(samdb, setup_path(\"provision.ldif\"),", "= samba.param.default_path() if not os.path.exists(os.path.dirname(smbconf)): os.makedirs(os.path.dirname(smbconf)) # only install a new smb.conf if", "+ configdn if sitename is None: sitename=DEFAULTSITE names = ProvisionNames() names.rootdn = rootdn", "sysvol: Physical path for the sysvol folder :param dnsdomain: The DNS name of", "The highest USN modified by this upgrade\"\"\" tab = [] tab.append(\"%s-%s\" % (low,", "external IPv4 address has been found. Using loopback.\") hostip = '127.0.0.1' else: hostip", "am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this wipes all existing data! \"\"\" if", "db :param lp: an LP object \"\"\" # Set ACL for GPO root", "SAMBA 4 with a next_rid of %u, \" % (next_rid) error += \"the", "sam.ldb This field is used to track range of USN modified by provision", "lp: Loadparm context :param session_info: Session information :param credentials: Credentials \"\"\" if lp.get(\"realm\")", "for inclusion in a named.conf file (including GSS-TSIG configuration). :param paths: all paths", "or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not", "serverrole is None: raise ProvisioningError(\"guess_names: 'server role' not specified in supplied %s!\" %", "documentation required for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN =", "not replace: entry = samdb.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE, \"dn\"]) for e", "\"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\"", "may call this, and then populate the database. :note: This will wipe the", "bits to a secrets database. :param secretsdb: Ldb Handle to the secrets database", "be ready to use\") logger.info(\"Server Role: %s\" % serverrole) logger.info(\"Hostname: %s\" % names.hostname)", "serverrole }) logger.info(\"Setting up sam.ldb rootDSE\") setup_samdb_rootdse(samdb, names) except Exception: samdb.transaction_cancel() raise else:", "see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is not None", "\" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\":", "am_rodc=am_rodc) # Set the NTDS settings DN manually - in order to have", "\"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"DESCRIPTOR\": descr,", "sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\" % LAST_PROVISION_USN_ATTRIBUTE, base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx =", "root user. :param nobody_uid: uid of the UNIX nobody user. :param users_gid: gid", "loading an empty smb.conf gives, then we need to be smarter. # Pretend", "hostip6=hostip6, hostname=names.hostname, realm=names.realm, domainguid=domainguid, ntdsguid=names.ntdsguid) create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir,", "None self.smbconf = None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field provisionUSN", "spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir,", "of the License, or # (at your option) any later version. # #", "ntdsguid: GUID of the hosts nTDSDSA record. \"\"\" assert isinstance(domainguid, str) if hostip6", "ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM Database. :note: This", "\"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid, \"HOSTIP6_BASE_LINE\": hostip6_base_line, \"HOSTIP6_HOST_LINE\": hostip6_host_line, \"GC_MSDCS_IP_LINE\": gc_msdcs_ip_line, \"GC_MSDCS_IP6_LINE\":", "users_gid=users_gid, wheel_gid=wheel_gid) if serverrole == \"domain controller\": # Set up group policies (domain", "with new schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False,", "os import re import pwd import grp import logging import time import uuid", "names.rootdn = rootdn names.domaindn = domaindn names.configdn = configdn names.schemadn = schemadn names.ldapmanagerdn", "KeyError: bind_gid = None if targetdir is not None: smbconf = os.path.join(targetdir, \"etc\",", ":note: caution, this wipes all existing data! \"\"\" if domainsid is None: domainsid", "high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE)", "specified by file\"\"\" return os.path.join(samba.param.setup_dir(), file) # Descriptors of naming contexts and other", "\"hku.ldb\" paths.hkpd = \"hkpd.ldb\" paths.hkpt = \"hkpt.ldb\" paths.sysvol = lp.get(\"path\", \"sysvol\") paths.netlogon =", "dir = \" + os.path.abspath(targetdir) lp.set(\"lock dir\", os.path.abspath(targetdir)) else: privatedir_line = \"\" lockdir_line", "os.path.join(root, name), SYSVOL_ACL, str(domainsid)) # Set acls on Policy folder and policies folders", "\"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass, domainsid,", "dnsdomain: The DNS name of the domain :param domaindn: The DN of the", "\"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return names def make_smbconf(smbconf, hostname, domain, realm,", "smb.conf file and let provision generate it\" % lp.configfile) if lp.get(\"realm\").upper() != realm:", "the sysvol share and the subfolders :param samdb: An LDB object on the", "lp is None: lp = samba.param.LoadParm() #Load non-existant file if os.path.exists(smbconf): lp.load(smbconf) if", "is not None: msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression tries to ensure", "set in the resulting smb.conf f = open(smbconf, mode='w') lp.dump(f, False) f.close() def", "not None: hostip6_base_line = \" IN AAAA \" + hostip6 hostip6_host_line = hostname", ":param subst_vars: Dictionary with substitution variables. \"\"\" assert ldb is not None ldb.transaction_start()", "or group from a list of possibilities. :param nssfn: NSS Function to try", "below, but we need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality)", "provision generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain controller\":", "be equal to netbios hostname '%s'!\" % (realm, netbiosname)) if domain == realm:", ":param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"), { \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn,", "for secure DNS \" \"updates\", paths.namedtxt) lastProvisionUSNs = get_last_provision_usn(samdb) maxUSN = get_max_usn(samdb, str(names.rootdn))", "\"standalone\" if sid_generator is None: sid_generator = \"internal\" assert domain is not None", "paths.namedconf_update) def create_named_txt(path, realm, dnsdomain, private_dir, keytab_name): \"\"\"Write out a file containing zone", "OpenLDAPBackend, ) import samba.param import samba.registry from samba.schema import Schema from samba.samdb import", "\"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"S:(AU;SA;WPWOWD;;;WD)(AU;SA;CR;;;BA)(AU;SA;CR;;;DU)\" \\ \"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_domain_descriptor(domain_sid):", "An LDB object on the SAM db :param netlogon: Physical path for the", "names.configdn}) check_all_substituted(display_specifiers_ldif) samdb.add_ldif(display_specifiers_ldif) logger.info(\"Adding users container\") setup_add_ldif(samdb, setup_path(\"provision_users_add.ldif\"), { \"DOMAINDN\": names.domaindn}) logger.info(\"Modifying users", "http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx if policyguid is None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc", "Schema from samba.samdb import SamDB VALID_NETBIOS_CHARS = \" !#$%&'()-.@^_{}~\" DEFAULT_POLICY_GUID = \"31B2F340-016D-11D2-945F-00C04FB984F9\" DEFAULT_DC_POLICY_GUID", "a secrets database. :param secretsdb: Ldb Handle to the secrets database :param machinepass:", "SEC_CHAN_BDC and dnsname is not None: # we are a domain controller then", "be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of", "None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap, str(domainsid),", "file and let provision generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole", "information :param credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb", "% lp.configfile) serverrole = serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") == \"\": raise", "is None: serverrole = lp.get(\"server role\") assert serverrole in (\"domain controller\", \"member server\",", "\\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "__str__(self): return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was not", "session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None,", "type selected\") provision_backend.init() provision_backend.start() # only install a new shares config db if", "names list. \"\"\" for name in names: try: return nssfn(name) except KeyError: pass", "up SAM db\") samdb = setup_samdb(paths.samdb, session_info, provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema,", "it\" % lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must", "= secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] =", "already if os.path.exists(smbconf): # if Samba Team members can't figure out the weird", "policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None,", "canchown = False else: canchown = True # Set the SYSVOL_ACL on the", "time, # but we don't delete the old record that we are about", "msg[\"objectSid\"] = [ndr_pack(domainsid)] # This complex expression tries to ensure that we don't", "freeze the zone while we update the contents if targetdir is None: rndc", "\"ldapi://%s\" % urllib.quote(paths.s4_ldapi_path, safe=\"\") schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\":", "= None self.domaindn = None self.configdn = None self.schemadn = None self.ldapmanagerdn =", "\"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(A;;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)(A;CIIO;RPWPCRCCLCLORCWOWDSDSW;;;DA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\"", "r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx + 1", "= \"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid) return policy_path def", "os.system(rndc + \" freeze \" + lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\":", "not None if not os.path.isdir(paths.netlogon): os.makedirs(paths.netlogon, 0755) if samdb_fill == FILL_FULL: setup_name_mappings(samdb, idmap,", "= None self.realm = None self.netbiosname = None self.domain = None self.hostname =", "setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn}) if fill", "the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.netlogon is not None if", "try (should raise KeyError if not found) :param names: Names to check. :return:", "None: policyguid = DEFAULT_POLICY_GUID policyguid = policyguid.upper() if policyguid_dc is None: policyguid_dc =", "domain admin admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line", "None: lp = samba.param.LoadParm() lp.load(smbconf) names = guess_names(lp=lp, hostname=hostname, domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn,", "Set the SYSVOL_ACL on the sysvol folder and subfolder (first level) setntacl(lp,sysvol, SYSVOL_ACL,", "path: Path of the new named.conf file. :param dnsdomain: DNS Domain name :param", "causes problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb, \"flatname=%s,cn=Primary Domains\" % domain)) msg[\"secureChannelType\"]", ":param replace: A boolean indicating if the range should replace any existing one", "lp: Loadparm context \"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp) reg.mount_hive(hive,", "serverrole, targetdir, sid_generator, useeadb, lp=lp) if lp is None: lp = samba.param.LoadParm() lp.load(smbconf)", "try: msg[\"privateKeytab\"] = [res[0][\"privateKeytab\"][0]] except KeyError: pass try: msg[\"krb5Keytab\"] = [res[0][\"krb5Keytab\"][0]] except KeyError:", "domain :param domaindn: The DN of the domain (ie. DC=...) :param samdb: An", "\"DNSDOMAIN\": dnsdomain, \"HOSTNAME\": hostname, \"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\"", "delete the old record that we are about to modify, # because that", "\\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\", "if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin", "Various module (the password_hash module in particular) need # to know what level", "above files are installed, your Samba4 server will be ready to use\") logger.info(\"Server", "# remove forbidden chars newnbname = \"\" for x in netbiosname: if x.isalnum()", "server role '%s'! Please remove the smb.conf file and let provision generate it\"", "in %r\" % names) findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2] findnss_gid = lambda", "level which itself is higher than its actual DC function level (2008_R2). This", "Please remove the smb.conf file and let provision generate it\" % (lp.get(\"realm\").upper(), realm,", "\"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, }) # The LDIF here was created when the", "on this file # the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"),", "(C) <NAME> <<EMAIL>> 2005 # # This program is free software; you can", "gid: The GID of the \"Domain adminstrators\" group :param domainsid: The SID of", "\"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\"", "findnss_gid([wheel]) try: bind_gid = findnss_gid([\"bind\", \"named\"]) except KeyError: bind_gid = None if targetdir", "= configdn names.schemadn = schemadn names.ldapmanagerdn = \"CN=Manager,\" + rootdn names.dnsdomain = dnsdomain", "be # started next time logger.info(\"Use later the following commandline to start slapd,", "added or none (using transactions). :param ldb: LDB file to import into. :param", "the AD domain :param policyguid: GUID of the default domain policy :param policyguid_dc:", "base=\"\", scope=ldb.SCOPE_SUBTREE, attrs=[LAST_PROVISION_USN_ATTRIBUTE]) if len(entry): range = [] idx = 0 p =", ":param high: The highest USN modified by this upgrade :param replace: A boolean", "secrets_ldb except Exception: secrets_ldb.transaction_cancel() raise def setup_privileges(path, session_info, lp): \"\"\"Setup the privileges database.", "to bind gid %u\", dns_keytab_path, paths.bind_gid) logger.info(\"Please install the phpLDAPadmin configuration located at", "AAAA \" + hostip6 else: hostip6_base_line = \"\" hostip6_host_line = \"\" gc_msdcs_ip6_line =", "'%s' must not be equal to short host name '%s'!\" % (domain, netbiosname))", "machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None, schema=None, next_rid=1000): \"\"\"Setup a complete SAM", "logger.info(\"A Kerberos configuration suitable for Samba 4 has been \" \"generated at %s\",", "suitable for inclusion in a named.conf file (including GSS-TSIG configuration). :param path: Path", "lp.get(\"server role\") if serverrole is None: raise ProvisioningError(\"guess_names: 'server role' not specified in", "setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except Exception: samdb.transaction_cancel() raise", "= dnsdomain.lower() if serverrole is None: serverrole = lp.get(\"server role\") if serverrole is", "\"NEXTRID\": str(next_rid), \"DEFAULTSITE\": names.sitename, \"CONFIGDN\": names.configdn, \"POLICYGUID\": policyguid, \"DOMAIN_FUNCTIONALITY\": str(domainFunctionality), \"SAMBA_VERSION_STRING\": version })", "is not None: domainguid_line = \"objectGUID: %s\\n-\" % domainguid else: domainguid_line = \"\"", "None: dnsdomain = lp.get(\"realm\") if dnsdomain is None or dnsdomain == \"\": raise", "samba from samba import ( Ldb, check_all_substituted, in_source_tree, source_tree_topdir, read_and_sub_file, setup_file, substitute_var, valid_netbios_name,", "hostname :param realm: Realm name :param domainguid: GUID of the domain. :param ntdsguid:", "provision_backend, lp, names, logger=logger, domainsid=domainsid, schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid,", "domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its own domain.\"\"\" assert isinstance(invocationid, str) if", "setntacl(lp, os.path.join(root, name), acl, domsid) for name in dirs: setntacl(lp, os.path.join(root, name), acl,", "machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, aci=None, serverrole=None, dom_for_fun_level=None, ldap_backend_extra_port=None, ldap_backend_forced_uri=None,", "serverrole = serverrole.lower() realm = dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm", "hostip6_host_line = \"\" gc_msdcs_ip6_line = \"\" if hostip is not None: hostip_base_line =", "domainguid, policyguid, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid, serverrole, am_rodc=False, dom_for_fun_level=None,", "names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\": str(next_rid), \"SAMBA_VERSION_STRING\":", "then we need to be smarter. # Pretend it just didn't exist --abartlet", "controller # policy) create_default_gpo(paths.sysvol, names.dnsdomain, policyguid, policyguid_dc) setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain,", "!= \"{\": guid = \"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain, \"Policies\", guid)", "FILL_FULL: logger.info(\"Admin password: %s\" % adminpass) if provision_backend.type is not \"ldb\": if provision_backend.credentials.get_bind_dn()", "os.path.exists(keytab_path): os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb", "list setup_file(setup_path(\"spn_update_list\"), paths.spn_update_list, None) if paths.bind_gid is not None: try: os.chown(dns_dir, -1, paths.bind_gid)", "}) # reload the smb.conf lp.load(smbconf) # and dump it without any values", "[str(key_version_number)] msg[\"privateKeytab\"] = [\"secrets.keytab\"] msg[\"secret\"] = [machinepass] msg[\"samAccountName\"] = [\"%s$\" % netbiosname] msg[\"secureChannelType\"]", "backend_credentials.authentication_requested()): if backend_credentials.get_bind_dn() is not None: setup_add_ldif(secrets_ldb, setup_path(\"secrets_simple_ldap.ldif\"), { \"LDAPMANAGERDN\": backend_credentials.get_bind_dn(), \"LDAPMANAGERPASS_B64\": b64encode(backend_credentials.get_password())", "privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\") idmap = setup_idmapdb(paths.idmapdb, session_info=session_info,", "have received a copy of the GNU General Public License # along with", "setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"), { \"REALM\": realm, \"DNSDOMAIN\": dnsdomain, \"DNS_KEYTAB\": dns_keytab_path, \"DNSPASS_B64\": b64encode(dnspass), \"HOSTNAME\": names.hostname,", "object on the SAM db :param lp: an LP object \"\"\" # Set", "realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE, \"NTDSGUID\": ntdsguid,", "= ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum !=", ":param lp: Loadparm context \"\"\" reg = samba.registry.Registry() hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp)", "setup_add_ldif(samdb, setup_path(\"provision.ldif\"), { \"CREATTIME\": str(int(time.time() * 1e7)), # seconds -> ticks \"DOMAINDN\": names.domaindn,", "paths: paths object :param dnsdomain: DNS Domain name :param domaindn: DN of the", "dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid =", "DEFAULT_DC_POLICY_GUID = \"6AC1786C-016F-11D2-945F-00C04fB984F9\" DEFAULTSITE = \"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an", "== \"domain controller\": create_dns_update_list(lp, logger, paths) provision_backend.post_setup() provision_backend.shutdown() create_phpldapadmin_config(paths.phpldapadminconfig, ldapi_url) except Exception: secrets_ldb.transaction_cancel()", "\"Default-First-Site-Name\" LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path to the provision", "scope=ldb.SCOPE_BASE) if len(res) == 1: msg[\"priorSecret\"] = [res[0][\"secret\"][0]] msg[\"priorWhenChanged\"] = [res[0][\"whenChanged\"][0]] try: msg[\"privateKeytab\"]", "LDIF file to load :param subst_vars: Optional variables to subsitute in LDIF. :param", "the right msDS-SupportedEncryptionTypes into the DB # In future, this might be determined", "os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is", "% provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None: # now display slapd_command_file.txt to show", "%s or see the template at %s\" % (paths.smbconf, setup_path(\"provision.smb.conf.dc\"))) assert paths.sysvol is", "setup_add_ldif(ldb, ldif_path, subst_vars) except Exception: ldb.transaction_cancel() raise else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set", "new schema\") except Exception: samdb.transaction_cancel() raise else: samdb.transaction_commit() samdb = SamDB(session_info=admin_session_info, auto_connect=False, credentials=provision_backend.credentials,", "scope=ldb.SCOPE_BASE) assert isinstance(names.ntdsguid, str) # Setup fSMORoleOwner entries to point at the newly", "2005 # # This program is free software; you can redistribute it and/or", "setup_modify_ldif(samdb, setup_path(\"provision_rootdse_modify.ldif\")) secretsdb_self_join(secrets_ldb, domain=names.domain, realm=names.realm, dnsdomain=names.dnsdomain, netbiosname=names.netbiosname, domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set", "range should replace any existing one or appended (default) \"\"\" tab = []", "InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal", "the base DN of the provision (ie. DC=foo, DC=bar) :return: The biggest USN", "domainguid_line = \"\" descr = b64encode(get_domain_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_basedn.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid),", "lp=lp) share_ldb.load_ldif_file_add(setup_path(\"share.ldif\")) logger.info(\"Setting up secrets.ldb\") secrets_ldb = setup_secretsdb(paths, session_info=session_info, backend_credentials=provision_backend.secrets_credentials, lp=lp) try: logger.info(\"Setting", "chown it dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None:", "session_info: Session information :param credentials: Credentials :param lp: Loadparm context \"\"\" reg =", "logger.info(\"Adding configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr,", "with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if not os.environ.has_key('SAMBA_SELFTEST'): logger.error(\"Failed to", "modifictions below, but we need them set from the start. samdb.set_opaque_integer(\"domainFunctionality\", domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\",", "be stored locally but in LDAP. \"\"\" assert session_info is not None #", "high): \"\"\"Set the field provisionUSN in sam.ldb This field is used to track", "lp.get(\"server role\") assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if invocationid is", "= logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger, system_session(), None, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, rootdn=rootdn,", "is None: schemadn = \"CN=Schema,\" + configdn if sitename is None: sitename=DEFAULTSITE names", "== realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to short domain", "% provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is not None:", "paths.netlogon, paths.sysvol, wheel_gid, domainsid, names.dnsdomain, names.domaindn, lp) logger.info(\"Setting up sam.ldb rootDSE marking as", "high, replace=False): \"\"\"Update the field provisionUSN in sam.ldb This field is used to", "default is %u.\" % ( 1000, 1000000000, 1000) raise ProvisioningError(error) # ATTENTION: Do", "was not a valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name", "\"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"), paths.namedconf_update) def create_named_txt(path,", "else: hostip = hostips[0] if len(hostips) > 1: logger.warning(\"More than one IPv4 address", "are emulating. # These will be fixed into the database via the database", "let provision generate it\" % (lp.get(\"server role\").upper(), serverrole, lp.configfile)) if serverrole == \"domain", "backup=None, serverrole=None, ldap_backend=None, ldap_backend_type=None, sitename=None, debuglevel=1): logger = logging.getLogger(\"provision\") samba.set_debug_level(debuglevel) res = provision(logger,", "if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to", "of the domain :param domaindn: The DN of the domain (ie. DC=...) \"\"\"", "== realm: raise ProvisioningError(\"guess_names: Realm '%s' must not be equal to netbios hostname", "% (realm, netbiosname)) if domain == realm: raise ProvisioningError(\"guess_names: Realm '%s' must not", "(newnbname, x) # force the length to be <16 netbiosname = newnbname[0:15] assert", "is not None if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = hostname.upper()", "dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line, \"HOSTIP_HOST_LINE\": hostip_host_line, \"DOMAINGUID\": domainguid, \"DATESTRING\": time.strftime(\"%Y%m%d%H\"), \"DEFAULTSITE\": DEFAULTSITE,", "the domain (ie. DC=...) \"\"\" try: os.chown(sysvol, -1, gid) except OSError: canchown =", "lp.configfile) if lp.get(\"realm\").upper() != realm: raise ProvisioningError(\"guess_names: 'realm=%s' in %s must match chosen", "session_info is not None # We use options=[\"modules:\"] to stop the modules loading", "forestFunctionality = dom_for_fun_level # Also wipes the database setup_samdb_partitions(path, logger=logger, lp=lp, provision_backend=provision_backend, session_info=session_info,", "nobody user. :param users_gid: gid of the UNIX users group. :param wheel_gid: gid", "= open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid,", "ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the field provisionUSN in sam.ldb", "invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\" % (names.hostname, names.dnsdomain), \"MACHINEPASS_B64\": b64encode(machinepass.encode('utf-16-le')), \"DOMAINSID\": str(domainsid), \"DCRID\":", "paths: all paths :param realm: Realm name :param dnsdomain: DNS Domain name :param", "LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\": provision_backend = ExistingBackend(backend_type,", "OSError: canchown = False else: canchown = True # Set the SYSVOL_ACL on", "a valid NetBIOS name.\"\"\" def __init__(self, name): super(InvalidNetbiosName, self).__init__( \"The name '%r' is", "# we don't want to create a domain that cannot allocate rids. if", "None: krbtgtpass = samba.generate_random_password(128, 255) if machinepass is None: machinepass = samba.generate_random_password(128, 255)", "privdir = os.path.join(targetdir, \"private\") else: privdir = lp.get(\"private dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if", "sid_generator = \"internal\" if backend_type == \"fedora-ds\": sid_generator = \"backend\" root_uid = findnss_uid([root", "import into. :param ldif_path: Path to the LDIF file. :param subst_vars: Dictionary with", "Credentials \"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb = Ldb(lp.get(\"sam database\"),", "database. :note: This function does not handle exceptions and transaction on purpose, it's", "keytab_name=paths.dns_keytab) logger.info(\"See %s for an example configuration include file for BIND\", paths.namedconf) logger.info(\"and", "result.paths = paths result.lp = lp result.samdb = samdb return result def provision_become_dc(smbconf=None,", "details. # # You should have received a copy of the GNU General", "os.path.exists(path): os.unlink(path) idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp) idmap_ldb.erase() idmap_ldb.load_ldif_file_add(setup_path(\"idmap_init.ldif\")) return idmap_ldb def setup_samdb_rootdse(samdb,", "expression=\"\", scope=ldb.SCOPE_ONELEVEL) for policy in res: acl = ndr_unpack(security.descriptor, str(policy[\"nTSecurityDescriptor\"])).as_sddl() policy_path = getpolicypath(sysvol,", "gc_msdcs_ip6_line = \"gc._msdcs IN AAAA \" + hostip6 else: hostip6_base_line = \"\" hostip6_host_line", "secretsdb: Ldb Handle to the secrets database :param machinepass: Machine password \"\"\" try:", "krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, root=None, nobody=None, users=None, wheel=None, backup=None, serverrole=None,", "if not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\")", "names.serverdn = \"CN=%s,CN=Servers,CN=%s,CN=Sites,%s\" % ( netbiosname, sitename, configdn) return names def make_smbconf(smbconf, hostname,", "ldapadminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None, ntdsguid=None, dnspass=None, root=None, nobody=None, users=None, wheel=None,", ":param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass setup_ldb(secretsdb, setup_path(\"secrets_dns.ldif\"),", ":note: This will wipe the main SAM database file! \"\"\" # Provision does", "session_info, lp): \"\"\"Setup the idmap database. :param path: path to the idmap database", "an LP object \"\"\" # Set ACL for GPO root folder root_policy_path =", "setup_ds_path=None, slapd_path=None, nosync=False, ldap_dryrun_mode=False, useeadb=False, am_rodc=False, lp=None): \"\"\"Provision samba4 :note: caution, this wipes", "if hostname is None: hostname = socket.gethostname().split(\".\")[0] netbiosname = lp.get(\"netbios name\") if netbiosname", "secretsdb.rename(res[0].dn, msg.dn) else: spn = [ 'HOST/%s' % shortname ] if secure_channel_type ==", "we computed earlier samdb.set_schema(schema) # Set the NTDS settings DN manually - in", "= DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is None: adminpass = samba.generate_random_password(12, 32)", "(C) <NAME> <<EMAIL>> 2007-2010 # Copyright (C) <NAME> <<EMAIL>> 2008-2009 # Copyright (C)", "substitution variables. \"\"\" assert ldb is not None ldb.transaction_start() try: setup_add_ldif(ldb, ldif_path, subst_vars)", "set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp, str(domainsid)) def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn,", "\"\"\" # Set ACL for GPO root folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\")", "re-initialise the database, not start it up try: os.unlink(samdb_path) except OSError: pass samdb", "lp.configfile)) if lp.get(\"server role\").lower() != serverrole: raise ProvisioningError(\"guess_names: 'server role=%s' in %s must", "other important objects # \"get_schema_descriptor\" is located in \"schema.py\" def get_sites_descriptor(domain_sid): sddl =", "# the substitution is done at runtime by samba_dnsupdate setup_file(setup_path(\"dns_update_list\"), paths.dns_update_list, None) setup_file(setup_path(\"spn_update_list\"),", "schema=schema, domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level,", "(newnbname, x) #force the length to be <16 netbiosname = newnbname[0:15] else: netbiosname", "% (newnbname, x) # force the length to be <16 netbiosname = newnbname[0:15]", "dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None shortname = netbiosname.lower()", "None for no controls \"\"\" assert isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data,", "tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] =", "secrets database :param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except OSError: pass", "logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend = FDSBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names,", "smbconfsuffix = \"member\" elif serverrole == \"standalone\": smbconfsuffix = \"standalone\" if sid_generator is", "will handle # it, and it causes problems for modifies anyway msg =", "private_dir: Path to private directory :param keytab_name: File name of DNS keytab file", "dir\"), \"sysvol\") netlogon = os.path.join(sysvol, realm.lower(), \"scripts\") setup_file(setup_path(\"provision.smb.conf.%s\" % smbconfsuffix), smbconf, { \"NETBIOS_NAME\":", "object. :param sid: The domain sid. :param domaindn: The domain DN. :param root_uid:", "Samba4 specific and should be replaced by the correct # DNS AD-style setup", "backend\" if provision_backend.type is not \"ldb\": ldap_backend_line = \"ldapBackend: %s\" % provision_backend.ldap_uri samdb.transaction_start()", "domain.upper() assert realm is not None realm = realm.upper() if lp is None:", "% names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if samdb_fill == FILL_FULL: logger.info(\"Admin password:", "dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, next_rid=next_rid) if serverrole == \"domain controller\": if paths.netlogon is None: logger.info(\"Existing", "'other', 'staff']) if wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid =", "database. Alternatively, provision() may call this, and then populate the database. :note: This", "\"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)\"", "samdb.transaction_start() try: logger.info(\"Setting up sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb,", "]) msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass):", "# Only make a zone file on the first DC, it should be", "locally but in LDAP. \"\"\" assert session_info is not None # We use", "admin_session_info = admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line = \"objectGUID:", "all LDIF data will be added or none (using transactions). :param ldb: LDB", "for the keytab code to update. spn.extend([ 'HOST/%s' % dnsname ]) msg[\"servicePrincipalName\"] =", "dnsdomain = realm.lower() dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower()) else: dnsname = None", "domain=domain, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, configdn=configdn, schemadn=schemadn, serverdn=serverdn, sitename=sitename) paths = provision_paths_from_lp(lp, names.dnsdomain) paths.bind_gid", "this upgrade :param replace: A boolean indicating if the range should replace any", "realm is not None realm = realm.upper() if lp is None: lp =", "% (realm, domain)) if rootdn is None: rootdn = domaindn if configdn is", "\"\" dns_dir = os.path.dirname(paths.dns) try: shutil.rmtree(dns_dir, True) except OSError: pass os.mkdir(dns_dir, 0775) #", "acl, lp, domsid): setntacl(lp, path, acl, domsid) for root, dirs, files in os.walk(path,", "not os.path.exists(policy_path): os.makedirs(policy_path, 0775) open(os.path.join(policy_path, \"GPT.INI\"), 'w').write( \"[General]\\r\\nVersion=0\") p = os.path.join(policy_path, \"MACHINE\") if", "setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn =", "up a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import b64encode import os", "names): \"\"\"Setup the SamDB rootdse. :param samdb: Sam Database handle \"\"\" setup_add_ldif(samdb, setup_path(\"provision_rootdse_add.ldif\"),", "samdb.write_prefixes_from_schema() samdb.add_ldif(schema.schema_data, controls=[\"relax:0\"]) setup_add_ldif(samdb, setup_path(\"aggregate_schema.ldif\"), {\"SCHEMADN\": names.schemadn}) logger.info(\"Reopening sam.ldb with new schema\") except", "attribute=\"objectGUID\") assert isinstance(domainguid, str) # Only make a zone file on the first", "grp import logging import time import uuid import socket import urllib import shutil", "samba.idmap import IDmapDB from samba.ms_display_specifiers import read_ms_ldif from samba.ntacls import setntacl, dsacl2fsacl from", "samdb, lp) def provision(logger, session_info, credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, domaindn=None, schemadn=None,", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "schema won't be loaded from the # DB samdb.connect(path) if fill == FILL_DRS:", "the domain :param domaindn: The DN of the domain (ie. DC=...) \"\"\" try:", "\\ \"(A;CI;RPWPCRCCLCLORCWOWDSDSW;;;BA)\" \\ \"(A;;RP;;;WD)\" \\ \"(A;;RPLCLORC;;;ED)\" \\ \"(A;;RPLCLORC;;;AU)\" \\ \"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)\" \\ \"S:AI(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)\" \\", "== \"domain controller\": # Set up group policies (domain policy and domain controller", "next_rid > 1000000000: error = \"You want to run SAMBA 4 with a", "out a file containing zone statements suitable for inclusion in a named.conf file", "if wheel is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try:", "schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, invocationid=None, machinepass=None,", "LDAP server ldapadminpass=samba.generate_random_password(128, 255) if backend_type is None: backend_type = \"ldb\" sid_generator =", "= read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify a ldb in", "idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid + \"-513\",", "if fill == FILL_DRS: return samdb samdb.transaction_start() try: # Set the domain functionality", "= ExistingBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"fedora-ds\": provision_backend", "must not be equal to netbios hostname '%s'!\" % (realm, netbiosname)) if domain", "nocontrols: Optional list of controls, can be None for no controls \"\"\" assert", ":param subst_vars: Optional dictionary with substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data,", "\\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;59ba2f42-79a2-11d0-9020-00c04fc2d3cf;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RP;037088f8-0ae1-11d2-b422-00a0c968f939;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)\" \\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)\" \\", "ldb in the private dir. :param ldb: LDB object. :param ldif_path: LDIF file", "self.smbconf = None def update_provision_usn(samdb, low, high, replace=False): \"\"\"Update the field provisionUSN in", ":param credentials: Credentials \"\"\" if lp.get(\"realm\") == \"\": raise Exception(\"Realm empty\") samdb =", "\"REALM\": realm, }) class ProvisioningError(Exception): \"\"\"A generic provision error.\"\"\" def __init__(self, value): self.value", "\"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\ \"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "security.random_sid() else: domainsid = security.dom_sid(domainsid) # create/adapt the group policy GUIDs # Default", "sid_generator, useeadb, lp=lp) else: make_smbconf(smbconf, hostname, domain, realm, serverrole, targetdir, sid_generator, useeadb, lp=lp)", "configuration container\") descr = b64encode(get_config_descriptor(domainsid)) setup_add_ldif(samdb, setup_path(\"provision_configuration_basedn.ldif\"), { \"CONFIGDN\": names.configdn, \"DESCRIPTOR\": descr, })", "low, high): \"\"\"Set the field provisionUSN in sam.ldb This field is used to", "netbiosname if not valid_netbios_name(domain): raise InvalidNetbiosName(domain) if hostname.upper() == realm: raise ProvisioningError(\"guess_names: Realm", "named.conf file. :param realm: Realm name :param dnsdomain: DNS Domain name :param private_dir:", "samdb.modify(msg) except ldb.LdbError, (enum, estr): if enum != ldb.ERR_NO_SUCH_ATTRIBUTE: # It might be", "ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) samdb.add(delta) def get_max_usn(samdb,basedn):", ":param dnsdomain: The DNS name of the domain :param domainsid: The SID of", "names.schemadn, \"DOMAINDN\": names.domaindn, \"ROOTDN\": names.rootdn, \"CONFIGDN\": names.configdn, \"SERVERDN\": names.serverdn, }) def setup_self_join(samdb, names,", "Session info. :param credentials: Credentials :param lp: Loadparm context :return: LDB handle for", "NTDSGUID based SPNs ntds_dn = \"CN=NTDS Settings,%s\" % names.serverdn names.ntdsguid = samdb.searchone(basedn=ntds_dn, attribute=\"objectGUID\",", "dnsdomain, \"REALM\": realm, \"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path,", "ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend =", "for the netlogon folder :param sysvol: Physical path for the sysvol folder :param", "selected\") provision_backend.init() provision_backend.start() # only install a new shares config db if there", "loaded from the # DB samdb.connect(path) if fill == FILL_DRS: return samdb samdb.transaction_start()", "}) setup_add_ldif(samdb, setup_path(\"provision_init.ldif\"), { \"BACKEND_TYPE\": provision_backend.type, \"SERVER_ROLE\": serverrole }) logger.info(\"Setting up sam.ldb rootDSE\")", "domain is not None domain = domain.upper() assert realm is not None realm", "idmap_ldb def setup_samdb_rootdse(samdb, names): \"\"\"Setup the SamDB rootdse. :param samdb: Sam Database handle", "%u, \" % (next_rid) error += \"the valid range is %u-%u. The default", "point at the newly created DC entry setup_modify_ldif(samdb, setup_path(\"provision_self_join_modify.ldif\"), { \"DOMAINDN\": names.domaindn, \"CONFIGDN\":", "os.makedirs(p, 0775) p = os.path.join(policy_path, \"USER\") if not os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath,", "LAST_PROVISION_USN_ATTRIBUTE = \"lastProvisionUSN\" def setup_path(file): \"\"\"Return an absolute path to the provision tempate", "a file into a LDB handle, optionally substituting variables. :note: Either all LDIF", "= Ldb(url=samdb_path, session_info=session_info, lp=lp, options=[\"modules:\"]) ldap_backend_line = \"# No LDAP backend\" if provision_backend.type", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License", "schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\":", "x) #force the length to be <16 netbiosname = newnbname[0:15] else: netbiosname =", "os.path.join(root, name), SYSVOL_ACL, str(domainsid)) for name in dirs: if canchown: os.chown(os.path.join(root, name), -1,", "entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab.append(str(e)) tab.append(\"%s-%s\" % (low, high)) delta = ldb.Message() delta.dn = ldb.Dn(samdb, \"@PROVISION\")", "handle # it, and it causes problems for modifies anyway msg = ldb.Message(ldb.Dn(secretsdb,", "else: ldb.transaction_commit() def provision_paths_from_lp(lp, dnsdomain): \"\"\"Set the default paths for provisioning. :param lp:", "realm, \"ZONE_FILE\": paths.dns, \"REALM_WC\": \"*.\" + \".\".join(realm.split(\".\")[1:]), \"NAMED_CONF\": paths.namedconf, \"NAMED_CONF_UPDATE\": paths.namedconf_update }) setup_file(setup_path(\"named.conf.update\"),", "str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499), }) # This is", "= \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb = os.path.join(paths.private_dir, lp.get(\"sam database\") or \"samdb.ldb\")", "dnsdomain == \"\": raise ProvisioningError(\"guess_names: 'realm' not specified in supplied %s!\", lp.configfile) dnsdomain", "not None realm = realm.upper() if lp is None: lp = samba.param.LoadParm() #Load", "database. :param path: Path to the privileges database. :param session_info: Session info. :param", "paths.winsdb = os.path.join(paths.private_dir, \"wins.ldb\") paths.s4_ldapi_path = os.path.join(paths.private_dir, \"ldapi\") paths.phpldapadminconfig = os.path.join(paths.private_dir, \"phpldapadmin-config.php\") paths.hklm", "= \"backend\" root_uid = findnss_uid([root or \"root\"]) nobody_uid = findnss_uid([nobody or \"nobody\"]) users_gid", "serverrole in (\"domain controller\", \"member server\", \"standalone\") if invocationid is None: invocationid =", "either version 3 of the License, or # (at your option) any later", "domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn, domain=domain, hostname=hostname, hostip=\"127.0.0.1\", domainsid=domainsid, machinepass=machinepass, serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\",", "length to be <16 netbiosname = newnbname[0:15] else: netbiosname = hostname.upper() if serverrole", "\"\"\" attrs = [\"whenChanged\", \"secret\", \"priorSecret\", \"priorChanged\", \"krb5Keytab\", \"privateKeytab\"] if realm is not", "\"@PROVISION\") delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) samdb.modify(delta) def set_provision_usn(samdb, low, high): \"\"\"Set the", "a named.conf file (including GSS-TSIG configuration). :param path: Path of the new named.conf", "logger.info(\"LDAP Admin User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if", "ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\", "tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1]) idx = idx + 1 return range else:", "unix names. :param samdb: SamDB object. :param idmap: IDmap db object. :param sid:", "\"DNS_KEYTAB\": keytab_name, \"DNS_KEYTAB_ABS\": os.path.join(private_dir, keytab_name), \"PRIVATE_DIR\": private_dir }) def create_krb5_conf(path, dnsdomain, hostname, realm):", "assert serverrole in (\"domain controller\", \"member server\", \"standalone\") if invocationid is None: invocationid", ":param hostname: Local hostname :param realm: Realm name \"\"\" setup_file(setup_path(\"krb5.conf\"), path, { \"DNSDOMAIN\":", "= hostname.upper() # remove forbidden chars newnbname = \"\" for x in netbiosname:", "= os.path.join(paths.private_dir, lp.get(\"secrets database\") or \"secrets.ldb\") paths.privilege = os.path.join(paths.private_dir, \"privilege.ldb\") paths.dns = os.path.join(paths.private_dir,", "modified by (upgrade)provision, 0 is this value is unknown \"\"\" entry = sam.search(expression=\"(&(dn=@PROVISION)(%s=*))\"", "serverrole is None: serverrole = \"standalone\" assert serverrole in (\"domain controller\", \"member server\",", "\"(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)\" \\ \"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;AU)\" \\ \"(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)\"", "values that are the default # this ensures that any smb.conf parameters that", "names.configdn, \"SCHEMADN\": names.schemadn, \"DOMAINDN\": names.domaindn, \"SERVERDN\": names.serverdn, \"INVOCATIONID\": invocationid, \"NETBIOSNAME\": names.netbiosname, \"DNSNAME\": \"%s.%s\"", ":param path: Path to write the configuration to. \"\"\" setup_file(setup_path(\"phpldapadmin-config.php\"), path, {\"S4_LDAPI_URI\": ldapi_uri})", "= hostname # remove forbidden chars newnbname = \"\" for x in netbiosname:", "None: # This will, for better or worse, default to 'WORKGROUP' domain =", "paths.bind_gid is not None: try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod", "\\ \"(OU;CIIOSA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967ab3-0de6-11d0-a285-00aa003049e2;WD)\" \\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl", "samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration data\") descr =", "{ \"POLICYGUID\": policyguid, \"POLICYGUID_DC\": policyguid_dc, \"DNSDOMAIN\": names.dnsdomain, \"DOMAINDN\": names.domaindn}) # add the NTDSGUID", "path: Path of the new named.conf file. :param realm: Realm name :param dnsdomain:", "if guid[0] != \"{\": guid = \"{%s}\" % guid policy_path = os.path.join(sysvolpath, dnsdomain,", "into. :param ldif_path: Path to the LDIF file. :param subst_vars: Dictionary with substitution", "be equal to short host name '%s'!\" % (domain, netbiosname)) else: domain =", "chmod needed to cope with umask os.chmod(dns_dir, 0775) os.chmod(paths.dns, 0664) except OSError: if", "'%s'!\" % (realm, domain)) if rootdn is None: rootdn = domaindn if configdn", "created secrets database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase()", "General Public License as published by # the Free Software Foundation; either version", "Loadparm context :param session_info: Session information :param credentials: Credentials \"\"\" if lp.get(\"realm\") ==", "logger.error(\"Failed to chown %s to bind gid %u\" % ( dns_dir, paths.bind_gid)) if", "sam: An LDB object pointing to the sam.ldb :return: an integer corresponding to", "won't work!\") domainFunctionality = dom_for_fun_level forestFunctionality = dom_for_fun_level # Also wipes the database", "schema = Schema(domainsid, invocationid=invocationid, schemadn=names.schemadn) if backend_type == \"ldb\": provision_backend = LDBBackend(backend_type, paths=paths,", "join\") setup_self_join(samdb, names=names, invocationid=invocationid, dnspass=dnspass, machinepass=machinepass, domainsid=domainsid, next_rid=next_rid, policyguid=policyguid, policyguid_dc=policyguid_dc, domainControllerFunctionality=domainControllerFunctionality, ntdsguid=ntdsguid) ntds_dn", "# backend code for provisioning a Samba4 server # Copyright (C) <NAME> <<EMAIL>>", "to the secrets database :param machinepass: Machine password \"\"\" try: os.unlink(os.path.join(private_dir, dns_keytab_path)) except", "'%s' must not be equal to short domain name '%s'!\" % (realm, domain))", "the # DB samdb.connect(path) if fill == FILL_DRS: return samdb samdb.transaction_start() try: #", "(\"domain controller\", \"member server\", \"standalone\") if invocationid is None: invocationid = str(uuid.uuid4()) if", "% names.domain) logger.info(\"DNS Domain: %s\" % names.dnsdomain) logger.info(\"DOMAIN SID: %s\" % str(domainsid)) if", "database :param session_info: Session information :param credentials: Credentials :param lp: Loadparm context \"\"\"", "= dnsdomain.upper() if lp.get(\"realm\") == \"\": raise ProvisioningError(\"guess_names: 'realm =' was not specified", "import ldb from samba.auth import system_session, admin_session import samba from samba import (", "names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum, estr):", "= netbiosname.lower() # We don't need to set msg[\"flatname\"] here, because rdn_name will", "# Default GUID for default policy are described at # \"How Core Group", "# this ensures that any smb.conf parameters that were set # on the", "def __str__(self): return \"ProvisioningError: \" + self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was", "\\ \"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)\" sec = security.descriptor.from_sddl(sddl, domain_sid) return ndr_pack(sec) def get_config_descriptor(domain_sid): sddl = \"O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)\"", "privileges database. :param path: Path to the privileges database. :param session_info: Session info.", "settings DN manually - in order to have it already around # before", "settings. \"\"\" assert smbconf is not None if hostname is None: hostname =", "zone while we update the contents if targetdir is None: rndc = '", "the range should replace any existing one or appended (default) \"\"\" tab =", "LDB handle, optionally substituting variables. :note: Either all LDIF data will be added", "dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality, ntdsguid): \"\"\"Join a host to its", "in dirs: setntacl(lp, os.path.join(root, name), acl, domsid) def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb,", "policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if adminpass is None:", "0 p = re.compile(r'-') for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]: tab = p.split(str(r)) range.append(tab[0]) range.append(tab[1])", "is None: # Make a new, random password between Samba and it's LDAP", "smb.conf f = open(smbconf, mode='w') lp.dump(f, False) f.close() def setup_name_mappings(samdb, idmap, sid, domaindn,", "a Samba configuration.\"\"\" __docformat__ = \"restructuredText\" from base64 import b64encode import os import", "targetdir=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None, domain=None, hostname=None, domainsid=None, adminpass=<PASSWORD>, krbtgtpass=None, domainguid=None,", "domainFunctionality) samdb.set_opaque_integer(\"forestFunctionality\", forestFunctionality) samdb.set_opaque_integer(\"domainControllerFunctionality\", domainControllerFunctionality) samdb.set_domain_sid(str(domainsid)) samdb.set_invocation_id(invocationid) logger.info(\"Adding DomainDN: %s\" % names.domaindn) #", "raise if serverrole == \"domain controller\": secretsdb_setup_dns(secrets_ldb, names, paths.private_dir, realm=names.realm, dnsdomain=names.dnsdomain, dns_keytab_path=paths.dns_keytab, dnspass=dnspass)", "suitable for inclusion in a named.conf file (including GSS-TSIG configuration). :param paths: all", "provision_backend.credentials.get_bind_dn() is not None: logger.info(\"LDAP Backend Admin DN: %s\" % provision_backend.credentials.get_bind_dn()) else: logger.info(\"LDAP", "provision_backend = LDBBackend(backend_type, paths=paths, lp=lp, credentials=credentials, names=names, logger=logger) elif backend_type == \"existing\": provision_backend", "+ self.value class InvalidNetbiosName(Exception): \"\"\"A specified name was not a valid NetBIOS name.\"\"\"", "domain = lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() != domain: raise ProvisioningError(\"guess_names: Workgroup", "realm=None, dnsdomain=None, keytab_path=None, key_version_number=1, secure_channel_type=SEC_CHAN_WKSTA): \"\"\"Add domain join-specific bits to a secrets database.", "file and let provision generate it\" % (lp.get(\"workgroup\").upper(), domain, lp.configfile)) if domaindn is", "attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm, str(domainsid), str(msg.dn))), scope=ldb.SCOPE_ONELEVEL) for del_msg in res: secretsdb.delete(del_msg.dn)", "dnsdomain = lp.get(\"realm\") if dnsdomain is None or dnsdomain == \"\": raise ProvisioningError(\"guess_names:", "idmap.setup_name_mapping(sid + \"-513\", idmap.TYPE_GID, users_gid) def setup_samdb_partitions(samdb_path, logger, lp, session_info, provision_backend, names, schema,", "dnsdomain = dnsdomain.lower() if serverrole is None: serverrole = lp.get(\"server role\") if serverrole", "default paths for provisioning. :param lp: Loadparm context. :param dnsdomain: DNS Domain name", "is None: wheel_gid = findnss_gid([\"wheel\", \"adm\"]) else: wheel_gid = findnss_gid([wheel]) try: bind_gid =", "policy :param policyguid_dc: GUID of the default domain controler policy \"\"\" policy_path =", "\\ \"(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)\" \\ \"(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;IF)\" \\ \"(OA;;RP;c7407360-20bf-11d0-a768-00aa006e0529;;RU)\" \\ \"(OA;;RP;b8119fd0-04f6-4762-ab7a-4986c76b3f9a;;RU)\" \\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\", "# This program is distributed in the hope that it will be useful,", "for inclusion in a named.conf file (including GSS-TSIG configuration). :param path: Path of", "serverrole=\"domain controller\", sitename=sitename) res.lp.set(\"debuglevel\", str(debuglevel)) return res def create_phpldapadmin_config(path, ldapi_uri): \"\"\"Create a PHP", "+ lp.get(\"realm\")) setup_file(setup_path(\"provision.zone\"), paths.dns, { \"HOSTNAME\": hostname, \"DNSDOMAIN\": dnsdomain, \"REALM\": realm, \"HOSTIP_BASE_LINE\": hostip_base_line,", "domainsid=domainsid, machinepass=<PASSWORD>, secure_channel_type=SEC_CHAN_BDC) # Now set up the right msDS-SupportedEncryptionTypes into the DB", "None self.netbiosname = None self.domain = None self.hostname = None self.sitename = None", "users_gid, wheel_gid): \"\"\"setup reasonable name mappings for sam names to unix names. :param", "\"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir, \"share.ldb\") paths.samdb =", "exist --abartlet data = open(smbconf, 'r').read() data = data.lstrip() if data is None", "the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php\", paths.phpldapadminconfig) logger.info(\"Once the above files", "lp=lp) logger.info(\"Setting up the privileges database\") setup_privileges(paths.privilege, session_info, lp=lp) logger.info(\"Setting up idmap db\")", "getpolicypath(sysvolpath,dnsdomain,policyguid_dc) create_gpo_struct(policy_path) def setup_samdb(path, session_info, provision_backend, lp, names, logger, domainsid, domainguid, policyguid, policyguid_dc,", "os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb = Ldb(path, session_info=session_info, lp=lp)", "loading - we # just want to wipe and re-initialise the database, not", "They have a big impact on the whole program! domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2 if", "try: os.chown(dns_dir, -1, paths.bind_gid) os.chown(paths.dns, -1, paths.bind_gid) # chmod needed to cope with", "is None: netbiosname = hostname # remove forbidden chars newnbname = \"\" for", "indicating if the range should replace any existing one or appended (default) \"\"\"", "dir\") lp.set(\"posix:eadb\", os.path.abspath(os.path.join(privdir, \"eadb.tdb\"))) if targetdir is not None: privatedir_line = \"private dir", "\\ \"(OA;CIIO;RPLCLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;CIIO;RPLCLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)\" \\ \"(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)\" \\ \"(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)\" \\ \"(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)\" \\", "LDB object pointing to the sam.ldb :return: an integer corresponding to the highest", "name mappings for sam names to unix names. :param samdb: SamDB object. :param", "start slapd, then Samba:\") logger.info(provision_backend.slapd_command_escaped) logger.info(\"This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh\", provision_backend.ldapdir)", "setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')), \"KRBTGTPASS_B64\": b64encode(krbtgtpass.encode('utf-16-le'))", "LDIF file path. :param subst_vars: Optional dictionary with substitution variables. \"\"\" data =", "\"\"\" idmap.setup_name_mapping(\"S-1-5-7\", idmap.TYPE_UID, nobody_uid) idmap.setup_name_mapping(\"S-1-5-32-544\", idmap.TYPE_GID, wheel_gid) idmap.setup_name_mapping(sid + \"-500\", idmap.TYPE_UID, root_uid) idmap.setup_name_mapping(sid", "domainguid=domainguid, policyguid=policyguid, policyguid_dc=policyguid_dc, fill=samdb_fill, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, invocationid=invocationid, machinepass=machinepass, dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc,", "names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif", "and groups\") setup_add_ldif(samdb, setup_path(\"provision_users.ldif\"), { \"DOMAINDN\": names.domaindn, \"DOMAINSID\": str(domainsid), \"CONFIGDN\": names.configdn, \"ADMINPASS_B64\": b64encode(adminpass.encode('utf-16-le')),", "Session information :param credentials: Credentials :param lp: Loadparm context \"\"\" if os.path.exists(path): os.unlink(path)", "os.unlink(keytab_path) dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab) if os.path.exists(dns_keytab_path): os.unlink(dns_keytab_path) path = paths.secrets secrets_ldb =", "--abartlet data = open(smbconf, 'r').read() data = data.lstrip() if data is None or", "session_info: Session information :param credentials: Credentials :param lp: Loadparm context \"\"\" if os.path.exists(path):", "names.serverdn) samdb.connect(path) samdb.transaction_start() try: samdb.invocation_id = invocationid logger.info(\"Setting up sam.ldb configuration data\") descr", "record that we are about to modify, # because that would delete the", "FDSBackend, LDBBackend, OpenLDAPBackend, ) import samba.param import samba.registry from samba.schema import Schema from", "os.path.exists(p): os.makedirs(p, 0775) def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc): \"\"\"Create the default GPO for", "logger, lp, session_info, provision_backend, names, schema, serverrole, erase=False): \"\"\"Setup the partitions for the", "\"\"\"Set the field provisionUSN in sam.ldb This field is used to track range", "= admin_session(lp, str(domainsid)) samdb.set_session_info(admin_session_info) if domainguid is not None: domainguid_line = \"objectGUID: %s\\n-\"", "yet samdb = SamDB(session_info=session_info, url=None, auto_connect=False, credentials=provision_backend.credentials, lp=lp, global_schema=False, am_rodc=am_rodc) logger.info(\"Pre-loading the Samba", "domain :param guid: The GUID of the policy :return: A string with the", "folder root_policy_path = os.path.join(sysvol, dnsdomain, \"Policies\") setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid)) res = samdb.search(base=\"CN=Policies,CN=System,%s\"%(domaindn),", "substitution variables. \"\"\" data = read_and_sub_file(ldif_path, subst_vars) ldb.modify_ldif(data, controls) def setup_ldb(ldb, ldif_path, subst_vars):", "if serverrole is None: serverrole = lp.get(\"server role\") assert serverrole in (\"domain controller\",", "the sysvol folder :param dnsdomain: The DNS name of the domain :param domainsid:", "new named.conf file. :param realm: Realm name :param dnsdomain: DNS Domain name :param", "credentials=credentials, names=names, logger=logger, domainsid=domainsid, schema=schema, hostname=hostname, ldapadminpass=<PASSWORD>, slapd_path=slapd_path, ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls, nosync=nosync, ldap_backend_forced_uri=ldap_backend_forced_uri)", "}) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), { \"DOMAINDN\": names.domaindn}) setup_modify_ldif(samdb, setup_path(\"provision_configuration_references.ldif\"), { \"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn})", "def findnss(nssfn, names): \"\"\"Find a user or group from a list of possibilities.", "% names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except ldb.LdbError, (enum,", "samdb.transaction_cancel() raise else: samdb.transaction_commit() return samdb FILL_FULL = \"FULL\" FILL_NT4SYNC = \"NT4SYNC\" FILL_DRS", "remove the smb.conf file and let provision generate it\" % (lp.get(\"realm\").upper(), realm, lp.configfile))", "\"CONFIGDN\": names.configdn, \"SCHEMADN\": names.schemadn, \"DEFAULTSITE\": names.sitename, \"SERVERDN\": names.serverdn, \"NETBIOSNAME\": names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid +", "samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE, name=\"msDS-SupportedEncryptionTypes\") samdb.modify(msg) except", "paths.netlogon is not None if paths.sysvol is None: logger.info(\"Existing smb.conf does not have", "FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more", "names.serverdn, }) def setup_self_join(samdb, names, machinepass, dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc, domainControllerFunctionality,", "ldap_backend_extra_port=ldap_backend_extra_port, ldap_dryrun_mode=ldap_dryrun_mode, root=root, setup_ds_path=setup_ds_path, ldap_backend_forced_uri=ldap_backend_forced_uri) elif backend_type == \"openldap\": provision_backend = OpenLDAPBackend(backend_type, paths=paths,", "sam.ldb partitions and settings\") setup_add_ldif(samdb, setup_path(\"provision_partitions.ldif\"), { \"SCHEMADN\": ldb.Dn(schema.ldb, names.schemadn).get_casefold(), \"CONFIGDN\": ldb.Dn(schema.ldb, names.configdn).get_casefold(),", "= policyguid.upper() if policyguid_dc is None: policyguid_dc = DEFAULT_DC_POLICY_GUID policyguid_dc = policyguid_dc.upper() if", "gc_msdcs_ip6_line = \"\" if hostip is not None: hostip_base_line = \" IN A", "database \"\"\" if os.path.exists(path): os.unlink(path) privilege_ldb = Ldb(path, session_info=session_info, lp=lp) privilege_ldb.erase() privilege_ldb.load_ldif_file_add(setup_path(\"provision_privilege.ldif\")) def", "names.netbiosname, \"RIDALLOCATIONSTART\": str(next_rid + 100), \"RIDALLOCATIONEND\": str(next_rid + 100 + 499), }) #", "msg[\"servicePrincipalName\"] = spn secretsdb.add(msg) def secretsdb_setup_dns(secretsdb, names, private_dir, realm, dnsdomain, dns_keytab_path, dnspass): \"\"\"Add", "User: %s\" % provision_backend.credentials.get_username()) logger.info(\"LDAP Admin Password: %s\" % provision_backend.credentials.get_password()) if provision_backend.slapd_command_escaped is", "install a new smb.conf if there isn't one there already if os.path.exists(smbconf): #", "does not have a [netlogon] share, but you are configuring a DC.\") logger.info(\"Please", "isinstance(ldif_path, str) data = read_and_sub_file(ldif_path, subst_vars) ldb.add_ldif(data, controls) def setup_modify_ldif(ldb, ldif_path, subst_vars=None,controls=[\"relax:0\"]): \"\"\"Modify", "specific and should be replaced by the correct # DNS AD-style setup setup_add_ldif(samdb,", "create_named_conf(paths, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir) create_named_txt(paths.namedtxt, realm=names.realm, dnsdomain=names.dnsdomain, private_dir=paths.private_dir, keytab_name=paths.dns_keytab) logger.info(\"See %s for an", "netbiosname.upper() if not valid_netbios_name(netbiosname): raise InvalidNetbiosName(netbiosname) if dnsdomain is None: dnsdomain = lp.get(\"realm\")", "-1, gid) except OSError: canchown = False else: canchown = True # Set", "modified by this upgrade :param high: The highest USN modified by this upgrade\"\"\"", "attribute in # \"secrets_dns.ldif\". paths.dns_keytab = \"dns.keytab\" paths.keytab = \"secrets.keytab\" paths.shareconf = os.path.join(paths.private_dir,", "try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"] = ldb.MessageElement( elements=kerberos_enctypes,", "kerberos_enctypes = str(ENC_ALL_TYPES) try: msg = ldb.Message(ldb.Dn(samdb, samdb.searchone(\"distinguishedName\", expression=\"samAccountName=%s$\" % names.netbiosname, scope=ldb.SCOPE_SUBTREE))) msg[\"msDS-SupportedEncryptionTypes\"]", "default to 'WORKGROUP' domain = lp.get(\"workgroup\") domain = domain.upper() if lp.get(\"workgroup\").upper() != domain:", "call this, and then populate the database. :note: This will wipe the Sam", "serverrole, \"NETLOGONPATH\": netlogon, \"SYSVOLPATH\": sysvol, \"SIDGENERATOR_LINE\": sid_generator_line, \"PRIVATEDIR_LINE\": privatedir_line, \"LOCKDIR_LINE\": lockdir_line }) #", "for the SAM database. Alternatively, provision() may call this, and then populate the", "keytab and previous password. res = secretsdb.search(base=\"cn=Primary Domains\", attrs=attrs, expression=(\"(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(dn=%s)))\" % (domain, realm,", "LDIF a file into a LDB handle, optionally substituting variables. :note: Either all", "= security.dom_sid(domainsid) # create/adapt the group policy GUIDs # Default GUID for default", "sid_generator is None: sid_generator = \"internal\" assert domain is not None domain =", "A boolean indicating if the range should replace any existing one or appended", "names.configdn, \"SERVERDN\": names.serverdn, \"RIDAVAILABLESTART\": str(next_rid + 600), \"POLICYGUID_DC\": policyguid_dc }) setup_modify_ldif(samdb, setup_path(\"provision_basedn_references.ldif\"), {", "is not None: try: os.chmod(dns_keytab_path, 0640) os.chown(dns_keytab_path, -1, paths.bind_gid) except OSError: if not", "\"\"\"Return an absolute path to the provision tempate file specified by file\"\"\" return", "of the new named.conf file. :param dnsdomain: DNS Domain name :param hostname: Local", "Only make a zone file on the first DC, it should be #", "name :param dnsdomain: DNS Domain name :param private_dir: Path to private directory :param", "policyguid_dc = policyguid_dc.upper() if adminpass is None: adminpass = samba.generate_random_password(12, 32) if krbtgtpass", "file into a LDB handle, optionally substituting variables. :note: Either all LDIF data" ]
[]
[ "and added to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu)", ",\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction)", "############################################################################# import os import sys from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt,", "self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar", "TODO # menubar help menu # TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40,", "\"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120)", "\"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of list", "self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i dont need this here,", "catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack)", "QSize from PyQt5 import QtCore from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import", "PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QSize from PyQt5 import QtCore from", "backend and added to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu)", "switch contents of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets", "QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar')", "stackwidget to switch contents of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) #", "self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" ,", "self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\")", "setup menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view =", "#self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series", "edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu #", "= QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow)", "be created in the backend and added to the stack. self.watchListTable = QTableWidget()", "PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget,", "PyQt5 import QtCore from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView,", "MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) #", "(QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class", "New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction)", "splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout = QHBoxLayout() self.centralWidget.setLayout(self.boxLayout) MainWindow.setCentralWidget(self.centralWidget) self.boxLayout.addWidget(self.splitter)", "QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow):", "Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow)", "= QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter =", "def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\")", "= QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter)", "QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple", "ヽ( ´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit =", "self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned')", "sure i dont need this here, it should be created in the backend", "self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction =", "dont need this here, it should be created in the backend and added", "QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\")", "self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1,", "14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion", "to switch contents of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add", "menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\")", "widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout = QHBoxLayout() self.centralWidget.setLayout(self.boxLayout)", "QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget,", "setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") # setup menubar menubar", "= QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\",", "= QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650])", "self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.')", "TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New", "QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ########################################################################################################", "from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout,", "super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") # setup", "self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\")", "QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget,", "# [nevermind lol] pretty sure i dont need this here, it should be", ",\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction)", "self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction =", "# TODO # menubar help menu # TODO # Toolbar self.toolbar = QToolBar(MainWindow)", "MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction =", "self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\",", "self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\",", "MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") # setup menubar menubar =", "= QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction)", "self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit", "should be created in the backend and added to the stack. self.watchListTable =", "file menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction", "75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)", "Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction", "Qt, QSize from PyQt5 import QtCore from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets", "<filename>sal_ui.py<gh_stars>0 ############################################################################# # dvneeseele ############################################################################# import os import sys from PyQt5.QtGui import QIcon", "self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central')", "# menubar file menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit", "QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i", "the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14))", "\"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to", "self.mb_help = menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction)", "= menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction", "from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget,", "menu # TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction =", "__init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") #", "(QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol]", "sys from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QSize from PyQt5 import", "self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") #", "= QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow)", "QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow)", "MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\")", "menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO", "self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\")", "self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction = QAction(\"Edit", "Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction)", "QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\")", "´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\")", "MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction =", "QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def", "self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\",", "menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu", "QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\"))", "import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction,", "QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction)", "menubar view menu # TODO # menubar help menu # TODO # Toolbar", "Anime Library | ヽ( ´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar() self.mb_file =", "menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction =", "Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents", "self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i dont need", "here, it should be created in the backend and added to the stack.", "self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140)", "\"Start Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch", "import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView)", "to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout = QHBoxLayout() self.centralWidget.setLayout(self.boxLayout) MainWindow.setCentralWidget(self.centralWidget)", "import QtCore from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar,", "# stackwidget to switch contents of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable)", "MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete", "import os import sys from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QSize", "MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO # menubar help menu #", "Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction", "Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of list catagories", "it should be created in the backend and added to the stack. self.watchListTable", "self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction = QAction(\"New", "= QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure", "self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start", "MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget =", "self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout", "salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ(", "os import sys from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QSize from", "in the backend and added to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows)", "to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial',", "from PyQt5.QtCore import Qt, QSize from PyQt5 import QtCore from PyQt5.QtGui import QFont,", "self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO #", "Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of list catagories self.tableStack =", "= menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar", "self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ########################################################################################################", "Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO # menubar help menu", "# menubar view menu # TODO # menubar help menu # TODO #", "self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack')", "lol] pretty sure i dont need this here, it should be created in", "Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator()", "menubar help menu # TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar)", ",\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal)", "self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\",", "MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar()", "menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction = QAction(\"New Entry\", MainWindow)", "self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\")", "self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i dont need this", "= QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow)", "# setup menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view", "self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\",", "# TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create", "self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout = QHBoxLayout() self.centralWidget.setLayout(self.boxLayout) MainWindow.setCentralWidget(self.centralWidget) self.boxLayout.addWidget(self.splitter) MainWindow.show()", "= QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar", "self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50,", "contents of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to", "40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\")", "self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N')", "self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\")", "MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar() self.mb_file", "class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library |", "QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO # menubar help", "need this here, it should be created in the backend and added to", "# menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view", "QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime", "# add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout =", "= QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction)", "MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25)", "self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i dont need this here, it", "self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow)", "view menu # TODO # menubar help menu # TODO # Toolbar self.toolbar", "= QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow)", "self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App", "PyQt5.QtCore import Qt, QSize from PyQt5 import QtCore from PyQt5.QtGui import QFont, QIcon", "QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library", "the backend and added to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection)", "QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def", "self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of list catagories self.tableStack = QStackedWidget(self.splitter)", ",\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) #############################################################################################################", "from PyQt5 import QtCore from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow,", "= QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction = QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow)", "self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\"", "[nevermind lol] pretty sure i dont need this here, it should be created", "# menubar help menu # TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40))", "import sys from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QSize from PyQt5", "sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind", "self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty", "menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help", "PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem,", "MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction", "# sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) #", "= QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7)", "############################################################################# # dvneeseele ############################################################################# import os import sys from PyQt5.QtGui import QIcon from", "help menu # TODO # Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction", "Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget", "Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0,", "self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction = QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar", "self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series Type\"])", "Library | ヽ( ´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\")", "menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar", "menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file", "list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter self.splitter.addWidget(self.sidebar)", "added to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers)", "self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App", "############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75)", "| ヽ( ´ー`)ノ\") # setup menubar menubar = MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit", "pretty sure i dont need this here, it should be created in the", "dvneeseele ############################################################################# import os import sys from PyQt5.QtGui import QIcon from PyQt5.QtCore import", ", \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of", "self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter)", "self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\",", "self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current')", "= MainWindow.menuBar() self.mb_file = menubar.addMenu(\"File\") self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help =", "of list catagories self.tableStack = QStackedWidget(self.splitter) self.tableStack.setObjectName('tablestack') self.tableStack.addWidget(self.watchListTable) # add widgets to splitter", "self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\")", "# dvneeseele ############################################################################# import os import sys from PyQt5.QtGui import QIcon from PyQt5.QtCore", "QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self):", "QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget)", "self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i dont need this here, it should", "QIcon from PyQt5.QtCore import Qt, QSize from PyQt5 import QtCore from PyQt5.QtGui import", "QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\", MainWindow) self.addnewAction.setShortcut('Ctrl+N') self.toolbar.addAction(self.addnewAction) self.deleteAction", "add widgets to splitter self.splitter.addWidget(self.sidebar) self.splitter.addWidget(self.tableStack) self.splitter.setSizes([50, 650]) ######################################################################################################## ######################################################################################################## self.boxLayout = QHBoxLayout()", "self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English", "menubar file menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu", "menu # TODO # menubar help menu # TODO # Toolbar self.toolbar =", ",\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction", "import Qt, QSize from PyQt5 import QtCore from PyQt5.QtGui import QFont, QIcon from", "QAbstractItemView, QToolBar, QSplitter, QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object):", "QtCore from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import (QMainWindow, QAbstractItemView, QToolBar, QSplitter,", "this here, it should be created in the backend and added to the", "# Toolbar self.toolbar = QToolBar(MainWindow) self.toolbar.setIconSize(QSize(40, 40)) MainWindow.addToolBar(self.toolbar) self.addnewAction = QAction(QIcon(\"icons/add_1.png\"),\"Create New Entry\",", "import QIcon from PyQt5.QtCore import Qt, QSize from PyQt5 import QtCore from PyQt5.QtGui", "self.mb_edit = menubar.addMenu(\"Edit\") self.mb_view = menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file menu", "self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\", \"SUB/DUB\",", "QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\",", "i dont need this here, it should be created in the backend and", "created in the backend and added to the stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable')", "from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QSize from PyQt5 import QtCore", "def setupUI(self, MainWindow): MainWindow.setWindowIcon(QIcon(\"icons/saldb_red\")) MainWindow.setWindowTitle(\"Simple Anime Library | ヽ( ´ー`)ノ\") # setup menubar", "self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\",", "= QAction(\"Edit Entry\", MainWindow) self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO # menubar", "= menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) #", "self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow)", "self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\",", "self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing') self.sidebar.addItem('Current') self.sidebar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # [nevermind lol] pretty sure i dont", "self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar =", "25) self.splitter.setStretchFactor(1, 75) # sidebar (QListWidget) self.sidebar = QListWidget(self.splitter) self.sidebar.setObjectName('sidebar') self.sidebar.addItem('Fin.') self.sidebar.addItem('Planned') self.sidebar.addItem('Ongoing')", "\"English Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) #", "\"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget to switch contents of list catagories self.tableStack", "QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__() def setupUI(self,", "self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget) self.splitter.setOrientation(Qt.Horizontal) self.splitter.setStretchFactor(0, 25) self.splitter.setStretchFactor(1, 75) #", "QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction = QAction(QIcon(\"icons/filter.png\") ,\"Filter/Sort\", MainWindow) self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator()", "Title\", \"SUB/DUB\", \"Start Date\" , \"Completion Date\", \"Series Type\"]) self.watchListTable.verticalHeader().setDefaultSectionSize(140) self.watchListTable.horizontalHeader().setDefaultSectionSize(120) # stackwidget", ",\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction)", "self.infoAction = QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter", "= menubar.addMenu(\"View\") self.mb_help = menubar.addMenu(\"Help\") # menubar file menu self.mb_newAction = QAction(\"New Entry\",", "menu self.mb_newAction = QAction(\"New Entry\", MainWindow) self.mb_file.addAction(self.mb_newAction) # menubar edit menu self.mb_editEntryAction =", "QHBoxLayout, QWidget, QAction, QStackedWidget, QListWidget, QTableWidget, QTableWidgetItem, QTableView) class salUI(object): def __init__(self): super(salUI).__init__()", "stack. self.watchListTable = QTableWidget() self.watchListTable.setObjectName('watchListTable') self.watchListTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False)", "MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction", "QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\")", "self.watchListTable.setSelectionMode(QAbstractItemView.SingleSelection) self.watchListTable.setContextMenuPolicy(Qt.CustomContextMenu) self.watchListTable.customContextMenuRequested.connect(self.tableContextMenu) self.watchListTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.watchListTable.setFont(QFont('Arial', 14)) self.watchListTable.setWordWrap(False) #self.watchListTable.setTextAlignment(Qt.AlignCenter) self.watchListTable.setColumnCount(7) self.watchListTable.setHorizontalHeaderLabels([\"Art\", \"Title\", \"English Title\",", "self.mb_edit.addAction(self.mb_editEntryAction) # menubar view menu # TODO # menubar help menu # TODO", "MainWindow) self.editAction.setShortcut(\"Ctrl+E\") self.toolbar.addAction(self.editAction) self.toolbar.addSeparator() self.findAction = QAction(QIcon(\"icons/find.png\") ,\"Search\", MainWindow) self.findAction.setShortcut(\"Ctrl+F\") self.toolbar.addAction(self.findAction) self.queryAction =", "self.queryAction.setShortcut(\"Ctrl+Alt+Q\") self.toolbar.addAction(self.queryAction) self.toolbar.addSeparator() self.settingsAction = QAction(QIcon(\"icons/settings.png\") ,\"App Settings\", MainWindow) self.settingsAction.setShortcut(\"Ctrl+Shift+S\") self.toolbar.addAction(self.settingsAction) self.infoAction =", "QAction(QIcon(\"icons/delete_1.png\") ,\"Delete Entry\", MainWindow) self.deleteAction.setShortcut(\"Ctrl+D\") self.toolbar.addAction(self.deleteAction) self.editAction = QAction(QIcon(\"icons/edit.png\") ,\"Edit Entry\", MainWindow) self.editAction.setShortcut(\"Ctrl+E\")", "QAction(QIcon(\"icons/info.png\") ,\"App Info\", MainWindow) self.toolbar.addAction(self.infoAction) ############################################################################################################# self.centralWidget = QWidget(MainWindow) self.centralWidget.setObjectName('central') self.splitter = QSplitter(self.centralWidget)" ]
[ "# vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com'", "open(path, 'rb'), } r = requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id =", "} r = requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data", "try: face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id", "detect(path): data = { 'api_key': API_KEY, 'api_secret': API_SECRET, } files = { 'img':", "API_SECRET, } files = { 'img': open(path, 'rb'), } r = requests.post(API_URL +", "= '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key': API_KEY, 'api_secret':", "'<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key':", "def detect(path): data = { 'api_key': API_KEY, 'api_secret': API_SECRET, } files = {", "{ 'img': open(path, 'rb'), } r = requests.post(API_URL + '/detection/detect', data=data, files=files) try:", "requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key':", "r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result =", "import requests API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path):", "'rb'), } r = requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"]", "face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id }", "-*- coding: utf-8 -*- # vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET =", "= '<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data = {", "API_KEY, 'api_secret': API_SECRET, } files = { 'img': open(path, 'rb'), } r =", "API_URL = 'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key': API_KEY, 'api_secret': API_SECRET, }", "{ 'api_key': API_KEY, 'api_secret': API_SECRET, } files = { 'img': open(path, 'rb'), }", "'api_key': API_KEY, 'api_secret': API_SECRET, } files = { 'img': open(path, 'rb'), } r", "= r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result", "coding: utf-8 -*- # vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET = '<KEY>'", "'img': open(path, 'rb'), } r = requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id", "{ 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result = requests.post(API_URL + '/detection/landmark',", "'/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret':", "'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result = requests.post(API_URL + '/detection/landmark', data=data)", "'<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key': API_KEY, 'api_secret': API_SECRET,", "= 'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key': API_KEY, 'api_secret': API_SECRET, } files", "} result = requests.post(API_URL + '/detection/landmark', data=data) return result.json() except: return -1 #", "result = requests.post(API_URL + '/detection/landmark', data=data) return result.json() except: return -1 # detect(u'source.jpg')", "-*- # vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL =", "API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data =", "'api_secret': API_SECRET, } files = { 'img': open(path, 'rb'), } r = requests.post(API_URL", "requests API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data", "= { 'api_key': API_KEY, 'api_secret': API_SECRET, } files = { 'img': open(path, 'rb'),", "face_id } result = requests.post(API_URL + '/detection/landmark', data=data) return result.json() except: return -1", "utf-8 -*- # vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL", "+ '/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY,", "'api_secret': API_SECRET, 'face_id': face_id } result = requests.post(API_URL + '/detection/landmark', data=data) return result.json()", "data = { 'api_key': API_KEY, 'api_secret': API_SECRET, } files = { 'img': open(path,", "API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result = requests.post(API_URL + '/detection/landmark', data=data) return", "API_SECRET, 'face_id': face_id } result = requests.post(API_URL + '/detection/landmark', data=data) return result.json() except:", "} files = { 'img': open(path, 'rb'), } r = requests.post(API_URL + '/detection/detect',", "API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key': API_KEY,", "data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret': API_SECRET,", "'http://apicn.faceplusplus.com' def detect(path): data = { 'api_key': API_KEY, 'api_secret': API_SECRET, } files =", "= requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data = {", "data = { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result = requests.post(API_URL", "files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data = { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id':", "= { 'api_key': API_KEY, 'api_secret': API_SECRET, 'face_id': face_id } result = requests.post(API_URL +", "= { 'img': open(path, 'rb'), } r = requests.post(API_URL + '/detection/detect', data=data, files=files)", "r = requests.post(API_URL + '/detection/detect', data=data, files=files) try: face_id = r.json()[\"face\"][0][\"face_id\"] data =", "vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET = '<KEY>' API_URL = 'http://apicn.faceplusplus.com' def", "'face_id': face_id } result = requests.post(API_URL + '/detection/landmark', data=data) return result.json() except: return", "files = { 'img': open(path, 'rb'), } r = requests.post(API_URL + '/detection/detect', data=data,", "# -*- coding: utf-8 -*- # vim:fenc=utf-8 import requests API_KEY = '<KEY>' API_SECRET" ]
[]
[ "ctx.send(\"You think you're funny huh?\") # makes the bot run with the bot", "think you're funny huh?\") # makes the bot run with the bot token", "other purpose you want @bot.command() async def test(ctx): # sends the message in", "def test(ctx): # sends the message in the quote await ctx.send(\"You think you're", "redditAPI import * # links to the roll features from roll import *", "now but you can use it for whatever other purpose you want @bot.command()", "# links to the redesigned help command from help import * # links", "for whatever other purpose you want @bot.command() async def test(ctx): # sends the", "import * # links to the various bot settings from setting import *", "the different \"sus\" features from sus import * # links to the soundboard", "want @bot.command() async def test(ctx): # sends the message in the quote await", "import * # links to the random sus meme feature from redditAPI import", "purpose you want @bot.command() async def test(ctx): # sends the message in the", "help command from help import * # links to the random sus meme", "you're funny huh?\") # makes the bot run with the bot token bot.run(bot_token)", "for now but you can use it for whatever other purpose you want", "other feature files # links to the redesigned help command from help import", "# sends the message in the quote await ctx.send(\"You think you're funny huh?\")", "settings from setting import * # links to the different \"sus\" features from", "in the quote await ctx.send(\"You think you're funny huh?\") # makes the bot", "feature files # links to the redesigned help command from help import *", "sus meme feature from redditAPI import * # links to the roll features", "to debug things; just a short message for now but you can use", "quote await ctx.send(\"You think you're funny huh?\") # makes the bot run with", "# links to the different \"sus\" features from sus import * # links", "purposes to debug things; just a short message for now but you can", "just a short message for now but you can use it for whatever", "setting import * # links to the different \"sus\" features from sus import", "# links to the various bot settings from setting import * # links", "the main bot file with the other feature files # links to the", "roll import * # links to the various bot settings from setting import", "import * # links to the roll features from roll import * #", "command from help import * # links to the random sus meme feature", "the roll features from roll import * # links to the various bot", "main bot file with the other feature files # links to the redesigned", "to the soundboard features from music import * # test command; used for", "* # links to the random sus meme feature from redditAPI import *", "things; just a short message for now but you can use it for", "# links to the random sus meme feature from redditAPI import * #", "bot file with the other feature files # links to the redesigned help", "links to the various bot settings from setting import * # links to", "features from sus import * # links to the soundboard features from music", "* # links to the different \"sus\" features from sus import * #", "you want @bot.command() async def test(ctx): # sends the message in the quote", "redesigned help command from help import * # links to the random sus", "whatever other purpose you want @bot.command() async def test(ctx): # sends the message", "* # links to the soundboard features from music import * # test", "from help import * # links to the random sus meme feature from", "the message in the quote await ctx.send(\"You think you're funny huh?\") # makes", "links to the different \"sus\" features from sus import * # links to", "different \"sus\" features from sus import * # links to the soundboard features", "from roll import * # links to the various bot settings from setting", "* # links to the various bot settings from setting import * #", "but you can use it for whatever other purpose you want @bot.command() async", "import * # links to the different \"sus\" features from sus import *", "sends the message in the quote await ctx.send(\"You think you're funny huh?\") #", "features from music import * # test command; used for test purposes to", "import * # links to the soundboard features from music import * #", "from sus import * # links to the soundboard features from music import", "# test command; used for test purposes to debug things; just a short", "random sus meme feature from redditAPI import * # links to the roll", "* # test command; used for test purposes to debug things; just a", "links the main bot file with the other feature files # links to", "debug things; just a short message for now but you can use it", "from redditAPI import * # links to the roll features from roll import", "short message for now but you can use it for whatever other purpose", "for test purposes to debug things; just a short message for now but", "sus import * # links to the soundboard features from music import *", "the redesigned help command from help import * # links to the random", "command; used for test purposes to debug things; just a short message for", "to the random sus meme feature from redditAPI import * # links to", "can use it for whatever other purpose you want @bot.command() async def test(ctx):", "await ctx.send(\"You think you're funny huh?\") # makes the bot run with the", "help import * # links to the random sus meme feature from redditAPI", "file with the other feature files # links to the redesigned help command", "message for now but you can use it for whatever other purpose you", "from setting import * # links to the different \"sus\" features from sus", "with the other feature files # links to the redesigned help command from", "<reponame>joonsauce/sus-bot<gh_stars>1-10 # links the main bot file with the other feature files #", "from music import * # test command; used for test purposes to debug", "the quote await ctx.send(\"You think you're funny huh?\") # makes the bot run", "roll features from roll import * # links to the various bot settings", "bot settings from setting import * # links to the different \"sus\" features", "to the roll features from roll import * # links to the various", "to the redesigned help command from help import * # links to the", "links to the redesigned help command from help import * # links to", "meme feature from redditAPI import * # links to the roll features from", "use it for whatever other purpose you want @bot.command() async def test(ctx): #", "features from roll import * # links to the various bot settings from", "test purposes to debug things; just a short message for now but you", "links to the roll features from roll import * # links to the", "# links to the soundboard features from music import * # test command;", "test command; used for test purposes to debug things; just a short message", "the soundboard features from music import * # test command; used for test", "* # links to the roll features from roll import * # links", "links to the soundboard features from music import * # test command; used", "\"sus\" features from sus import * # links to the soundboard features from", "message in the quote await ctx.send(\"You think you're funny huh?\") # makes the", "# links to the roll features from roll import * # links to", "@bot.command() async def test(ctx): # sends the message in the quote await ctx.send(\"You", "async def test(ctx): # sends the message in the quote await ctx.send(\"You think", "# links the main bot file with the other feature files # links", "to the various bot settings from setting import * # links to the", "the various bot settings from setting import * # links to the different", "files # links to the redesigned help command from help import * #", "the random sus meme feature from redditAPI import * # links to the", "you can use it for whatever other purpose you want @bot.command() async def", "test(ctx): # sends the message in the quote await ctx.send(\"You think you're funny", "import * # test command; used for test purposes to debug things; just", "the other feature files # links to the redesigned help command from help", "links to the random sus meme feature from redditAPI import * # links", "it for whatever other purpose you want @bot.command() async def test(ctx): # sends", "feature from redditAPI import * # links to the roll features from roll", "used for test purposes to debug things; just a short message for now", "various bot settings from setting import * # links to the different \"sus\"", "to the different \"sus\" features from sus import * # links to the", "a short message for now but you can use it for whatever other", "music import * # test command; used for test purposes to debug things;", "soundboard features from music import * # test command; used for test purposes" ]
[ "11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\":", "\"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8,", "4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 }", "\"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9,", "BASE_INDICES = { \"current_power\": 0, \"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4,", "\"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = {", "DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\":", "TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\":", "9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\": 13, \"l3_power\": 14, \"status\": 15", "2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES = {", "7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES = {", "<reponame>rcasula/KostalPyko BASE_INDICES = { \"current_power\": 0, \"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\":", "\"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, }", "\"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9,", "{ **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\":", "\"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\": 13, \"l3_power\": 14, \"status\":", "7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\":", "8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\": 13, \"l3_power\": 14,", "\"string2_current\": 9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7,", "{ **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11 }", "6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES,", "3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\":", "7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\": 13,", "\"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES,", "**BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\":", "\"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7", "10, \"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\":", "0, \"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6,", "= { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11", "\"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\": 13, \"l3_power\": 14, \"status\": 15 }", "} DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10,", "} TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10,", "= { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\":", "\"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES", "8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\":", "SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7,", "\"current_power\": 0, \"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\":", "\"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES =", "1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES", "{ **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8,", "\"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\": 13, \"l3_power\":", "\"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES,", "= { \"current_power\": 0, \"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\":", "\"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5, \"l1_power\": 6, } SINGLE_STRING_INDICES =", "9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\":", "5, \"l1_power\": 6, } SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES =", "= { **BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11,", "\"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12, \"string3_current\":", "**BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"string3_voltage\": 11, \"l3_voltage\": 12,", "} SINGLE_STRING_INDICES = { **BASE_INDICES, \"status\": 7 } DOUBLE_STRING_INDICES = { **BASE_INDICES, \"string2_voltage\":", "**BASE_INDICES, \"string2_voltage\": 7, \"l2_voltage\": 8, \"string2_current\": 9, \"l2_power\": 10, \"status\": 11 } TRIPLE_STRING_INDICES", "{ \"current_power\": 0, \"total_energy\": 1, \"daily_energy\": 2, \"string1_voltage\": 3, \"l1_voltage\": 4, \"string1_current\": 5," ]
[ "this object is ``'public'`` or ``'internal'`` Returns: Class or Function ''' assert level", "Class or Function ''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj):", "method, or property, return the module that is was defined in. This function", "_LEVELS: raise ValueError(\"Unknown API level %r, expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__", "version (tuple) : A version tuple ``(x,y,z)`` stating what version this object was", "the object public or internal Returns: bool ''' if level not in _LEVELS:", "object was first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import", "Returns: bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level): '''", "# Powered by the Bokeh Development Team. # # The full license is", ".future import wraps #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC", "assert level in _LEVELS def decorator(obj): # Keep track of how many public/internal", "Returns: Class or Function ''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #-----------------------------------------------------------------------------", "print_function, unicode_literals import logging logger = logging.getLogger(__name__) # This one module is exempted", "_get_module(obj) _increment_api_count(mod, level) # If we are decorating a class if isinstance(obj, type):", "Class or Function ''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- #", "''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args: obj", "by the Bokeh Development Team. # # The full license is in the", "{internal}) Whether to declare the object public or internal Returns: bool ''' if", "return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level return wrapper return decorator", "'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare", "property, return the module that is was defined in. This function is written", "def decorator(obj): # Keep track of how many public/internal things there are declared", "__bkapi__ dict on a module, creating a new one if necessary ''' if", "if necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ = {PUBLIC: 0, INTERNAL:0} mod.__bkapi__[level]", "have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {public} Args: version", "Returns: bool ''' if level not in _LEVELS: raise ValueError(\"Unknown API level %r,", "to be ``'public'``, introduced in ``version``. This decorator annotates a function or class", "object was introduced. Returns: Class or Function ''' return _access(version, 'internal') internal.__doc__ =", "a module so we can make sure api tests are comprehensive mod =", "is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj (object) :", "version __bklevel__ = {internal} Args: version (tuple) : A version tuple ``(x,y,z)`` stating", "This decorator annotates a function or class with information about what version it", ": A version tuple ``(x,y,z)`` stating what version this object was introduced. level:", "reserved. # # Powered by the Bokeh Development Team. # # The full", "''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #-----------------------------------------------------------------------------", "first introduced in, as well as that it is part of the internal", "it was first introduced in, as well as that it is part of", "public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj (object) : The function, class,", "''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import", "__bklevel__ = {public} Args: version (tuple) : A version tuple ``(x,y,z)`` stating what", "internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string import nice_join, format_docstring", "this object was introduced. Returns: Class or Function ''' return _access(version, 'internal') internal.__doc__", "_access(version, level): ''' Declare an object to be ``{{ level }}``, introduced in", "\"internal\", as well as note what Bokeh version the object was first introduced", "may be defined to be \"public\" or \"internal\", as well as note what", "object will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {public}", "an object to be ``'public'``, introduced in ``version``. This decorator annotates a function", "python __bkversion__ = version __bklevel__ = level Args: version (tuple) : A version", "the decorated object will have attributes: .. code-block:: python __bkversion__ = version __bklevel__", "whether it is a public or internal API level. Specifically, the decorated object", "written with the usages of the Bokeh codebase in mind, and may not", "#----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def", "obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args:", "ValueError(\"Unknown API level %r, expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ == level", "``{{ level }}``, introduced in ``version``. This generic decorator annotates a function or", "{public} Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version this", "we are decorating a function or method @wraps(obj) def wrapper(*args, **kw): return obj(*args,", "methods, and properties may be defined to be \"public\" or \"internal\", as well", "public or internal Returns: bool ''' if level not in _LEVELS: raise ValueError(\"Unknown", "module so we can make sure api tests are comprehensive mod = _get_module(obj)", "from ..util.string import nice_join, format_docstring from .future import wraps #----------------------------------------------------------------------------- # Globals and", "expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC),", "Whether this object is ``'public'`` or ``'internal'`` Returns: Class or Function ''' assert", "or Function ''' assert level in _LEVELS def decorator(obj): # Keep track of", "function is written with the usages of the Bokeh codebase in mind, and", "one if necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ = {PUBLIC: 0, INTERNAL:0}", "this software. #----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh API information. Within the", "in, as well as that it is part of the internal API. Specifically,", "API. Specifically, the decorated object will have attributes: .. code-block:: python __bkversion__ =", "class, method, or property to test Returns: bool ''' return hasattr(obj, '__bklevel__') and", "full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- '''", "in _LEVELS: raise ValueError(\"Unknown API level %r, expected %s\" % (level, nice_join(_LEVELS))) return", "obj (object) : The function, class, method, or property to declare a version", "% (level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def", "or internal API level. Specifically, the decorated object will have attributes: .. code-block::", "general ''' import sys if isinstance(obj, property): modname = obj.fget.__module__ else: modname =", "rights reserved. # # Powered by the Bokeh Development Team. # # The", "level. Specifically, the decorated object will have attributes: .. code-block:: python __bkversion__ =", "functions, classes, methods, and properties may be defined to be \"public\" or \"internal\",", "function, class, method, or property to test Returns: bool ''' return hasattr(obj, '__bklevel__')", "or class with information about what version it was first introduced in, as", "public(version): ''' Declare an object to be ``'public'``, introduced in ``version``. This decorator", "The function, class, method, or property to declare a level for level ({public}", "as well as whether it is a public or internal API level. Specifically,", "Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version, level): ''' Declare an", "= version __bklevel__ = {internal} Args: version (tuple) : A version tuple ``(x,y,z)``", "version __bklevel__ = {public} Args: version (tuple) : A version tuple ``(x,y,z)`` stating", "introduced in ``version``. This decorator annotates a function or class with information about", "level %r, expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ =", "''' Given an function, class, method, or property, return the module that is", "; public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string import", "__bkversion__ = version __bklevel__ = {internal} Args: version (tuple) : A version tuple", "'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object) : The", "= level return wrapper return decorator def _get_module(obj): ''' Given an function, class,", "return wrapper return decorator def _get_module(obj): ''' Given an function, class, method, or", "or {internal}) Whether to declare the object public or internal Returns: bool '''", "are decorating a class if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ = level", "else: modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the __bkapi__", "#----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an object to be", "method, or property to test Returns: bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj,", "property to declare a version for Returns: bool ''' return obj.__bkversion__ == version", "wraps #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public'", "#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. #", "unicode_literals import logging logger = logging.getLogger(__name__) # This one module is exempted from", "and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API", "# Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string import nice_join, format_docstring from .future", "return obj # Otherwise we are decorating a function or method @wraps(obj) def", "are declared # in a module so we can make sure api tests", "wrapper.__bklevel__ = level return wrapper return decorator def _get_module(obj): ''' Given an function,", "''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ = {PUBLIC: 0, INTERNAL:0} mod.__bkapi__[level] += 1", "code-block:: python __bkversion__ = version __bklevel__ = {internal} Args: version (tuple) : A", "introduced in, as well as that it is part of the internal API.", "api tests are comprehensive mod = _get_module(obj) _increment_api_count(mod, level) # If we are", "a public or internal API level. Specifically, the decorated object will have attributes:", "(object) : The function, class, method, or property to declare a level for", "public, internal ; public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from", "property to declare a level for level ({public} or {internal}) Whether to declare", "This one module is exempted from this :) # from bokeh.util.api import public,", "introduced. Returns: Class or Function ''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL))", "in ``version``. This generic decorator annotates a function or class with information about", "in. This function is written with the usages of the Bokeh codebase in", "of how many public/internal things there are declared # in a module so", "''' Declare an object to be ``{{ level }}``, introduced in ``version``. This", "**kw): return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level return wrapper return", "Team. # # The full license is in the file LICENSE.txt, distributed with", "``'public'``, introduced in ``version``. This decorator annotates a function or class with information", "exempted from this :) # from bokeh.util.api import public, internal ; public, internal", "def _access(version, level): ''' Declare an object to be ``{{ level }}``, introduced", "Specifically, the decorated object will have attributes: .. code-block:: python __bkversion__ = version", "as whether it is a public or internal API level. Specifically, the decorated", "# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # #", "_increment_api_count(mod, level) # If we are decorating a class if isinstance(obj, type): obj.__bkversion__", "what version it was first introduced in, as well as that it is", "division, print_function, unicode_literals import logging logger = logging.getLogger(__name__) # This one module is", "the __bkapi__ dict on a module, creating a new one if necessary '''", "in ``version``. This decorator annotates a function or class with information about what", "A version tuple ``(x,y,z)`` stating what version this object was introduced. level: (str)", "hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args: obj (object) : The function, class,", "new one if necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ = {PUBLIC: 0,", "one module is exempted from this :) # from bokeh.util.api import public, internal", "({public} or {internal}) Whether to declare the object public or internal Returns: bool", "Bokeh codebase in mind, and may not work in general ''' import sys", "``(x,y,z)`` stating what version this object was introduced. level: (str) Whether this object", "object is ``'public'`` or ``'internal'`` Returns: Class or Function ''' assert level in", "version tuple ``(x,y,z)`` stating what version this object was introduced. level: (str) Whether", "level): ''' Args: obj (object) : The function, class, method, or property to", "wrapper return decorator def _get_module(obj): ''' Given an function, class, method, or property,", "creating a new one if necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ =", "and properties may be defined to be \"public\" or \"internal\", as well as", "return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args: obj (object)", "\"public\" or \"internal\", as well as note what Bokeh version the object was", "Function ''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args:", "= [PUBLIC, INTERNAL] def _access(version, level): ''' Declare an object to be ``{{", "version this object was introduced. Returns: Class or Function ''' return _access(version, 'internal')", "introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function,", "= 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version): '''", "(c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by", "Function ''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API", "in a module so we can make sure api tests are comprehensive mod", "for Returns: bool ''' return obj.__bkversion__ == version def public(version): ''' Declare an", "things there are declared # in a module so we can make sure", "# The full license is in the file LICENSE.txt, distributed with this software.", "generic decorator annotates a function or class with information about what version it", "def public(version): ''' Declare an object to be ``'public'``, introduced in ``version``. This", "version it was first introduced in, as well as that it is part", "are decorating a function or method @wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw)", "of the Bokeh codebase in mind, and may not work in general '''", "well as note what Bokeh version the object was first introduced in. '''", "object will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {internal}", "#----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging logger = logging.getLogger(__name__)", "internal API level. Specifically, the decorated object will have attributes: .. code-block:: python", "def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level return", "import nice_join, format_docstring from .future import wraps #----------------------------------------------------------------------------- # Globals and constants #-----------------------------------------------------------------------------", "python __bkversion__ = version __bklevel__ = {internal} Args: version (tuple) : A version", "bool ''' if level not in _LEVELS: raise ValueError(\"Unknown API level %r, expected", "we can make sure api tests are comprehensive mod = _get_module(obj) _increment_api_count(mod, level)", "Updates the __bkapi__ dict on a module, creating a new one if necessary", "#----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string import nice_join, format_docstring from", "__bklevel__ = {internal} Args: version (tuple) : A version tuple ``(x,y,z)`` stating what", ":) # from bokeh.util.api import public, internal ; public, internal #----------------------------------------------------------------------------- # Imports", "this object was introduced. level: (str) Whether this object is ``'public'`` or ``'internal'``", "there are declared # in a module so we can make sure api", "attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {public} Args: version (tuple)", "first introduced in, as well as whether it is a public or internal", ".. code-block:: python __bkversion__ = version __bklevel__ = level Args: version (tuple) :", "``'internal'`` Returns: Class or Function ''' assert level in _LEVELS def decorator(obj): #", "This function is written with the usages of the Bokeh codebase in mind,", "2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the", "absolute_import, division, print_function, unicode_literals import logging logger = logging.getLogger(__name__) # This one module", "#----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version, level): '''", "internal Returns: bool ''' if level not in _LEVELS: raise ValueError(\"Unknown API level", "internal API. Specifically, the decorated object will have attributes: .. code-block:: python __bkversion__", "sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the __bkapi__ dict on a module, creating", "sys if isinstance(obj, property): modname = obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname]", ".. code-block:: python __bkversion__ = version __bklevel__ = {internal} Args: version (tuple) :", "property to test Returns: bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def", "level Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version this", "Whether to declare the object public or internal Returns: bool ''' if level", "with the usages of the Bokeh codebase in mind, and may not work", "Declare an object to be ``'public'``, introduced in ``version``. This decorator annotates a", "obj.__bkversion__ = version obj.__bklevel__ = level return obj # Otherwise we are decorating", "can make sure api tests are comprehensive mod = _get_module(obj) _increment_api_count(mod, level) #", "necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ = {PUBLIC: 0, INTERNAL:0} mod.__bkapi__[level] +=", "%s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL))", "version): ''' Args: obj (object) : The function, class, method, or property to", "a module, creating a new one if necessary ''' if not hasattr(mod, '__bkapi__'):", "# # Powered by the Bokeh Development Team. # # The full license", "it was first introduced in, as well as whether it is a public", "or internal Returns: bool ''' if level not in _LEVELS: raise ValueError(\"Unknown API", "``version``. This decorator annotates a function or class with information about what version", "version this object was introduced. Returns: Class or Function ''' return _access(version, 'public')", "isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ = level return obj # Otherwise we", "object was introduced. level: (str) Whether this object is ``'public'`` or ``'internal'`` Returns:", "as well as note what Bokeh version the object was first introduced in.", "level for level ({public} or {internal}) Whether to declare the object public or", "def is_declared(obj): ''' Args: obj (object) : The function, class, method, or property", "The function, class, method, or property to declare a version for Returns: bool", "''' Updates the __bkapi__ dict on a module, creating a new one if", "Class or Function ''' assert level in _LEVELS def decorator(obj): # Keep track", "defined to be \"public\" or \"internal\", as well as note what Bokeh version", "imports from ..util.string import nice_join, format_docstring from .future import wraps #----------------------------------------------------------------------------- # Globals", "- 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh", "def internal(version): ''' Declare an object to be ``'public'``, introduced in ``version``. This", "= version wrapper.__bklevel__ = level return wrapper return decorator def _get_module(obj): ''' Given", "''' if level not in _LEVELS: raise ValueError(\"Unknown API level %r, expected %s\"", "or property to declare a level for level ({public} or {internal}) Whether to", "the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide functions for declaring", "{internal} Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version this", "a function or class with information about what version it was first introduced", "logging logger = logging.getLogger(__name__) # This one module is exempted from this :)", "= version obj.__bklevel__ = level return obj # Otherwise we are decorating a", "code-block:: python __bkversion__ = version __bklevel__ = level Args: version (tuple) : A", "'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC,", "in _LEVELS def decorator(obj): # Keep track of how many public/internal things there", "well as that it is part of the internal API. Specifically, the decorated", "or property to declare a version for Returns: bool ''' return obj.__bkversion__ ==", "to be \"public\" or \"internal\", as well as note what Bokeh version the", "public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version, level):", "with this software. #----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh API information. Within", "return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): '''", "version this object was introduced. level: (str) Whether this object is ``'public'`` or", "internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj (object) : The function, class, method,", "internal ; public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string", "public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string import nice_join,", "introduced in, as well as whether it is a public or internal API", "or Function ''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): '''", "decorator annotates a function or class with information about what version it was", "are comprehensive mod = _get_module(obj) _increment_api_count(mod, level) # If we are decorating a", "# in a module so we can make sure api tests are comprehensive", "Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an object to be ``'public'``, introduced", "modname = obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): '''", "from __future__ import absolute_import, division, print_function, unicode_literals import logging logger = logging.getLogger(__name__) #", "information about what version it was first introduced in, as well as that", "method, or property to declare a version for Returns: bool ''' return obj.__bkversion__", "decorator(obj): # Keep track of how many public/internal things there are declared #", "part of the internal API. Specifically, the decorated object will have attributes: ..", "'__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args: obj (object) : The", "will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = level Args:", "object will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = level", "= obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates", "import logging logger = logging.getLogger(__name__) # This one module is exempted from this", "return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object)", "version it was first introduced in, as well as whether it is a", "obj (object) : The function, class, method, or property to declare a level", "an function, class, method, or property, return the module that is was defined", "as note what Bokeh version the object was first introduced in. ''' #-----------------------------------------------------------------------------", "logger = logging.getLogger(__name__) # This one module is exempted from this :) #", "be ``'public'``, introduced in ``version``. This decorator annotates a function or class with", "# from bokeh.util.api import public, internal ; public, internal #----------------------------------------------------------------------------- # Imports #-----------------------------------------------------------------------------", "format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object) : The function, class, method,", "# This one module is exempted from this :) # from bokeh.util.api import", "test Returns: bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level):", "Powered by the Bokeh Development Team. # # The full license is in", "codebase, functions, classes, methods, and properties may be defined to be \"public\" or", "__future__ import absolute_import, division, print_function, unicode_literals import logging logger = logging.getLogger(__name__) # This", "``(x,y,z)`` stating what version this object was introduced. Returns: Class or Function '''", "}}``, introduced in ``version``. This generic decorator annotates a function or class with", "(object) : The function, class, method, or property to declare a version for", "distributed with this software. #----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh API information.", "stating what version this object was introduced. Returns: Class or Function ''' return", "Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team.", "Provide functions for declaring Bokeh API information. Within the Bokeh codebase, functions, classes,", "class if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ = level return obj #", "declare a version for Returns: bool ''' return obj.__bkversion__ == version def public(version):", "This generic decorator annotates a function or class with information about what version", "#-----------------------------------------------------------------------------o def internal(version): ''' Declare an object to be ``'public'``, introduced in ``version``.", "Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public", "version tuple ``(x,y,z)`` stating what version this object was introduced. Returns: Class or", "[PUBLIC, INTERNAL] def _access(version, level): ''' Declare an object to be ``{{ level", "version the object was first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from", "# # The full license is in the file LICENSE.txt, distributed with this", "tuple ``(x,y,z)`` stating what version this object was introduced. level: (str) Whether this", "= logging.getLogger(__name__) # This one module is exempted from this :) # from", "is_level(obj, level): ''' Args: obj (object) : The function, class, method, or property", "from bokeh.util.api import public, internal ; public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- #", "information. Within the Bokeh codebase, functions, classes, methods, and properties may be defined", "(level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj,", "_LEVELS def decorator(obj): # Keep track of how many public/internal things there are", "is_declared(obj): ''' Args: obj (object) : The function, class, method, or property to", "in, as well as whether it is a public or internal API level.", "== version def public(version): ''' Declare an object to be ``'public'``, introduced in", "= format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def", "import absolute_import, division, print_function, unicode_literals import logging logger = logging.getLogger(__name__) # This one", "internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object) : The function,", "internal(version): ''' Declare an object to be ``'public'``, introduced in ``version``. This decorator", "== level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj", "track of how many public/internal things there are declared # in a module", "# If we are decorating a class if isinstance(obj, type): obj.__bkversion__ = version", "A version tuple ``(x,y,z)`` stating what version this object was introduced. Returns: Class", "Bokeh API information. Within the Bokeh codebase, functions, classes, methods, and properties may", "2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development", "decorating a function or method @wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__", "was defined in. This function is written with the usages of the Bokeh", "is was defined in. This function is written with the usages of the", "or property, return the module that is was defined in. This function is", "format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj (object) : The function,", "if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ = level return obj # Otherwise", "level return obj # Otherwise we are decorating a function or method @wraps(obj)", "a level for level ({public} or {internal}) Whether to declare the object public", "''' Args: obj (object) : The function, class, method, or property to test", "(str) Whether this object is ``'public'`` or ``'internal'`` Returns: Class or Function '''", "@wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level", "wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level return wrapper", "version def public(version): ''' Declare an object to be ``'public'``, introduced in ``version``.", "version obj.__bklevel__ = level return obj # Otherwise we are decorating a function", "defined in. This function is written with the usages of the Bokeh codebase", "classes, methods, and properties may be defined to be \"public\" or \"internal\", as", "= {public} Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version", "in mind, and may not work in general ''' import sys if isinstance(obj,", "what version this object was introduced. Returns: Class or Function ''' return _access(version,", "be defined to be \"public\" or \"internal\", as well as note what Bokeh", "Args: obj (object) : The function, class, method, or property to test Returns:", "file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh", "raise ValueError(\"Unknown API level %r, expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ ==", "function, class, method, or property to declare a level for level ({public} or", "information about what version it was first introduced in, as well as whether", "bool ''' return obj.__bkversion__ == version def public(version): ''' Declare an object to", ": The function, class, method, or property to test Returns: bool ''' return", "return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS", "def is_level(obj, level): ''' Args: obj (object) : The function, class, method, or", "well as whether it is a public or internal API level. Specifically, the", "__bkversion__ = version __bklevel__ = level Args: version (tuple) : A version tuple", "if isinstance(obj, property): modname = obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname] def", "obj.__bkversion__ == version def public(version): ''' Declare an object to be ``'public'``, introduced", "#----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging", "in general ''' import sys if isinstance(obj, property): modname = obj.fget.__module__ else: modname", "if level not in _LEVELS: raise ValueError(\"Unknown API level %r, expected %s\" %", "API level. Specifically, the decorated object will have attributes: .. code-block:: python __bkversion__", "and hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args: obj (object) : The function,", "``version``. This generic decorator annotates a function or class with information about what", "Given an function, class, method, or property, return the module that is was", "public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL]", "annotates a function or class with information about what version it was first", "about what version it was first introduced in, as well as whether it", "mind, and may not work in general ''' import sys if isinstance(obj, property):", "to declare a level for level ({public} or {internal}) Whether to declare the", "so we can make sure api tests are comprehensive mod = _get_module(obj) _increment_api_count(mod,", "not work in general ''' import sys if isinstance(obj, property): modname = obj.fget.__module__", "about what version it was first introduced in, as well as that it", "obj (object) : The function, class, method, or property to test Returns: bool", "obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the __bkapi__ dict on a", "= 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an object", "# Otherwise we are decorating a function or method @wraps(obj) def wrapper(*args, **kw):", "= level Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version", "it is a public or internal API level. Specifically, the decorated object will", "# Keep track of how many public/internal things there are declared # in", "= version __bklevel__ = level Args: version (tuple) : A version tuple ``(x,y,z)``", "have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = level Args: version", "= {internal} Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version", "is ``'public'`` or ``'internal'`` Returns: Class or Function ''' assert level in _LEVELS", "API level %r, expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__", "__bkversion__ = version __bklevel__ = {public} Args: version (tuple) : A version tuple", "license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide", "modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the __bkapi__ dict", "with information about what version it was first introduced in, as well as", "this :) # from bokeh.util.api import public, internal ; public, internal #----------------------------------------------------------------------------- #", "object to be ``{{ level }}``, introduced in ``version``. This generic decorator annotates", "Keep track of how many public/internal things there are declared # in a", "API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an object to be ``'public'``, introduced in", "decorated object will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ =", "method, or property to declare a level for level ({public} or {internal}) Whether", "comprehensive mod = _get_module(obj) _increment_api_count(mod, level) # If we are decorating a class", "# Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- #", "to be ``{{ level }}``, introduced in ``version``. This generic decorator annotates a", "Within the Bokeh codebase, functions, classes, methods, and properties may be defined to", "_access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object) :", "INTERNAL] def _access(version, level): ''' Declare an object to be ``{{ level }}``,", "usages of the Bokeh codebase in mind, and may not work in general", "isinstance(obj, property): modname = obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod,", "introduced in ``version``. This generic decorator annotates a function or class with information", "class, method, or property, return the module that is was defined in. This", "code-block:: python __bkversion__ = version __bklevel__ = {public} Args: version (tuple) : A", "or Function ''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private", "work in general ''' import sys if isinstance(obj, property): modname = obj.fget.__module__ else:", "level): ''' Updates the __bkapi__ dict on a module, creating a new one", "_get_module(obj): ''' Given an function, class, method, or property, return the module that", "the object was first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__", "level) # If we are decorating a class if isinstance(obj, type): obj.__bkversion__ =", "class with information about what version it was first introduced in, as well", "is exempted from this :) # from bokeh.util.api import public, internal ; public,", "(object) : The function, class, method, or property to test Returns: bool '''", "the Bokeh codebase, functions, classes, methods, and properties may be defined to be", ": The function, class, method, or property to declare a level for level", "Returns: Class or Function ''' assert level in _LEVELS def decorator(obj): # Keep", "method @wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ =", "for level ({public} or {internal}) Whether to declare the object public or internal", "functions for declaring Bokeh API information. Within the Bokeh codebase, functions, classes, methods,", "_increment_api_count(mod, level): ''' Updates the __bkapi__ dict on a module, creating a new", "attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {internal} Args: version (tuple)", "public or internal API level. Specifically, the decorated object will have attributes: ..", "= obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the __bkapi__ dict on", "in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide functions for", "sure api tests are comprehensive mod = _get_module(obj) _increment_api_count(mod, level) # If we", "or ``'internal'`` Returns: Class or Function ''' assert level in _LEVELS def decorator(obj):", "a function or method @wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ =", "attributes: .. code-block:: python __bkversion__ = version __bklevel__ = level Args: version (tuple)", "Bokeh version the object was first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #-----------------------------------------------------------------------------", "stating what version this object was introduced. level: (str) Whether this object is", "to declare the object public or internal Returns: bool ''' if level not", "module that is was defined in. This function is written with the usages", "If we are decorating a class if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__", "All rights reserved. # # Powered by the Bokeh Development Team. # #", "was first introduced in, as well as that it is part of the", "declare the object public or internal Returns: bool ''' if level not in", "to test Returns: bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj,", "return the module that is was defined in. This function is written with", "may not work in general ''' import sys if isinstance(obj, property): modname =", "or \"internal\", as well as note what Bokeh version the object was first", "declare a level for level ({public} or {internal}) Whether to declare the object", "we are decorating a class if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ =", "that is was defined in. This function is written with the usages of", "is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide functions", "version __bklevel__ = level Args: version (tuple) : A version tuple ``(x,y,z)`` stating", "Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.string import nice_join, format_docstring from .future import", "import sys if isinstance(obj, property): modname = obj.fget.__module__ else: modname = obj.__module__ return", "declared # in a module so we can make sure api tests are", "return decorator def _get_module(obj): ''' Given an function, class, method, or property, return", "API information. Within the Bokeh codebase, functions, classes, methods, and properties may be", "def _increment_api_count(mod, level): ''' Updates the __bkapi__ dict on a module, creating a", "type): obj.__bkversion__ = version obj.__bklevel__ = level return obj # Otherwise we are", "obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the", "= version __bklevel__ = {public} Args: version (tuple) : A version tuple ``(x,y,z)``", "''' Args: obj (object) : The function, class, method, or property to declare", "(tuple) : A version tuple ``(x,y,z)`` stating what version this object was introduced.", "is_version(obj, version): ''' Args: obj (object) : The function, class, method, or property", "is a public or internal API level. Specifically, the decorated object will have", "%r, expected %s\" % (level, nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__,", "this object was introduced. Returns: Class or Function ''' return _access(version, 'public') public.__doc__", "return sys.modules[modname] def _increment_api_count(mod, level): ''' Updates the __bkapi__ dict on a module,", "Bokeh codebase, functions, classes, methods, and properties may be defined to be \"public\"", "Inc. All rights reserved. # # Powered by the Bokeh Development Team. #", "constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o", "The function, class, method, or property to test Returns: bool ''' return hasattr(obj,", "a version for Returns: bool ''' return obj.__bkversion__ == version def public(version): '''", "first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division,", "#----------------------------------------------------------------------------- # Bokeh imports from ..util.string import nice_join, format_docstring from .future import wraps", "will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {internal} Args:", "module is exempted from this :) # from bokeh.util.api import public, internal ;", "# Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging logger", "was introduced. level: (str) Whether this object is ``'public'`` or ``'internal'`` Returns: Class", "Args: version (tuple) : A version tuple ``(x,y,z)`` stating what version this object", "internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object) : The function, class, method, or", "python __bkversion__ = version __bklevel__ = {public} Args: version (tuple) : A version", "function or method @wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ = version", "obj.__bklevel__ = level return obj # Otherwise we are decorating a function or", "level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj (object)", "on a module, creating a new one if necessary ''' if not hasattr(mod,", "was first introduced in, as well as whether it is a public or", "''' assert level in _LEVELS def decorator(obj): # Keep track of how many", "''' import sys if isinstance(obj, property): modname = obj.fget.__module__ else: modname = obj.__module__", "from .future import wraps #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal'", "return obj.__bkversion__ == version def public(version): ''' Declare an object to be ``'public'``,", "__bklevel__ = level Args: version (tuple) : A version tuple ``(x,y,z)`` stating what", "= level return obj # Otherwise we are decorating a function or method", "level ({public} or {internal}) Whether to declare the object public or internal Returns:", "format_docstring from .future import wraps #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL =", "= _get_module(obj) _increment_api_count(mod, level) # If we are decorating a class if isinstance(obj,", "version for Returns: bool ''' return obj.__bkversion__ == version def public(version): ''' Declare", "= format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj (object) : The function, class,", "declaring Bokeh API information. Within the Bokeh codebase, functions, classes, methods, and properties", "Bokeh imports from ..util.string import nice_join, format_docstring from .future import wraps #----------------------------------------------------------------------------- #", "from this :) # from bokeh.util.api import public, internal ; public, internal #-----------------------------------------------------------------------------", "logging.getLogger(__name__) # This one module is exempted from this :) # from bokeh.util.api", "object public or internal Returns: bool ''' if level not in _LEVELS: raise", "level in _LEVELS def decorator(obj): # Keep track of how many public/internal things", "class, method, or property to declare a version for Returns: bool ''' return", "# Bokeh imports from ..util.string import nice_join, format_docstring from .future import wraps #-----------------------------------------------------------------------------", "an object to be ``{{ level }}``, introduced in ``version``. This generic decorator", "mod = _get_module(obj) _increment_api_count(mod, level) # If we are decorating a class if", "Returns: Class or Function ''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def", "for declaring Bokeh API information. Within the Bokeh codebase, functions, classes, methods, and", "# Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an object to be ``'public'``,", "decorating a class if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ = level return", "level return wrapper return decorator def _get_module(obj): ''' Given an function, class, method,", "def _get_module(obj): ''' Given an function, class, method, or property, return the module", "function or class with information about what version it was first introduced in,", "that it is part of the internal API. Specifically, the decorated object will", "level }}``, introduced in ``version``. This generic decorator annotates a function or class", "wrapper.__bkversion__ = version wrapper.__bklevel__ = level return wrapper return decorator def _get_module(obj): '''", "software. #----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh API information. Within the Bokeh", "#----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh API information. Within the Bokeh codebase,", "as well as that it is part of the internal API. Specifically, the", "''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__, internal=repr(INTERNAL)) def is_declared(obj): ''' Args: obj", "# Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version, level): ''' Declare", "the usages of the Bokeh codebase in mind, and may not work in", "the Bokeh Development Team. # # The full license is in the file", "be \"public\" or \"internal\", as well as note what Bokeh version the object", "..util.string import nice_join, format_docstring from .future import wraps #----------------------------------------------------------------------------- # Globals and constants", "the module that is was defined in. This function is written with the", "property): modname = obj.fget.__module__ else: modname = obj.__module__ return sys.modules[modname] def _increment_api_count(mod, level):", "Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging logger =", "was introduced. Returns: Class or Function ''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__,", "''' Provide functions for declaring Bokeh API information. Within the Bokeh codebase, functions,", "in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals", "note what Bokeh version the object was first introduced in. ''' #----------------------------------------------------------------------------- #", "object was introduced. Returns: Class or Function ''' return _access(version, 'public') public.__doc__ =", "obj # Otherwise we are decorating a function or method @wraps(obj) def wrapper(*args,", "bokeh.util.api import public, internal ; public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh", "level): ''' Declare an object to be ``{{ level }}``, introduced in ``version``.", "nice_join(_LEVELS))) return obj.__bklevel__ == level is_level.__doc__ = format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version):", "is part of the internal API. Specifically, the decorated object will have attributes:", "''' Declare an object to be ``'public'``, introduced in ``version``. This decorator annotates", "format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version,", "make sure api tests are comprehensive mod = _get_module(obj) _increment_api_count(mod, level) # If", "Args: obj (object) : The function, class, method, or property to declare a", "what Bokeh version the object was first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate", "''' return obj.__bkversion__ == version def public(version): ''' Declare an object to be", "import wraps #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC =", "introduced. level: (str) Whether this object is ``'public'`` or ``'internal'`` Returns: Class or", "function, class, method, or property, return the module that is was defined in.", "LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide functions for declaring Bokeh API", "bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args:", "be ``{{ level }}``, introduced in ``version``. This generic decorator annotates a function", "and may not work in general ''' import sys if isinstance(obj, property): modname", "not in _LEVELS: raise ValueError(\"Unknown API level %r, expected %s\" % (level, nice_join(_LEVELS)))", "object to be ``'public'``, introduced in ``version``. This decorator annotates a function or", ": The function, class, method, or property to declare a version for Returns:", "= format_docstring(is_level.__doc__, public=repr(PUBLIC), internal=repr(INTERNAL)) def is_version(obj, version): ''' Args: obj (object) : The", "def is_version(obj, version): ''' Args: obj (object) : The function, class, method, or", "was first introduced in. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import,", "#----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version, level): ''' Declare an object to", "module, creating a new one if necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__", ".. code-block:: python __bkversion__ = version __bklevel__ = {public} Args: version (tuple) :", "a class if isinstance(obj, type): obj.__bkversion__ = version obj.__bklevel__ = level return obj", "Development Team. # # The full license is in the file LICENSE.txt, distributed", "what version it was first introduced in, as well as whether it is", "many public/internal things there are declared # in a module so we can", "is written with the usages of the Bokeh codebase in mind, and may", "level: (str) Whether this object is ``'public'`` or ``'internal'`` Returns: Class or Function", "hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__') def is_level(obj, level): ''' Args: obj (object) :", "function, class, method, or property to declare a version for Returns: bool '''", "decorator def _get_module(obj): ''' Given an function, class, method, or property, return the", "class, method, or property to declare a level for level ({public} or {internal})", "it is part of the internal API. Specifically, the decorated object will have", "tests are comprehensive mod = _get_module(obj) _increment_api_count(mod, level) # If we are decorating", "_LEVELS = [PUBLIC, INTERNAL] def _access(version, level): ''' Declare an object to be", "Bokeh Development Team. # # The full license is in the file LICENSE.txt,", "'__bkversion__') def is_level(obj, level): ''' Args: obj (object) : The function, class, method,", "will have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {public} Args:", "what version this object was introduced. level: (str) Whether this object is ``'public'``", "PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an", "the internal API. Specifically, the decorated object will have attributes: .. code-block:: python", "The full license is in the file LICENSE.txt, distributed with this software. #-----------------------------------------------------------------------------", "as that it is part of the internal API. Specifically, the decorated object", ": A version tuple ``(x,y,z)`` stating what version this object was introduced. Returns:", "level not in _LEVELS: raise ValueError(\"Unknown API level %r, expected %s\" % (level,", "public/internal things there are declared # in a module so we can make", "properties may be defined to be \"public\" or \"internal\", as well as note", "dict on a module, creating a new one if necessary ''' if not", "import public, internal ; public, internal #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports", "INTERNAL = 'internal' PUBLIC = 'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version):", "of the internal API. Specifically, the decorated object will have attributes: .. code-block::", "nice_join, format_docstring from .future import wraps #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL", "version wrapper.__bklevel__ = level return wrapper return decorator def _get_module(obj): ''' Given an", "to declare a version for Returns: bool ''' return obj.__bkversion__ == version def", "was introduced. Returns: Class or Function ''' return _access(version, 'internal') internal.__doc__ = format_docstring(internal.__doc__,", "``'public'`` or ``'internal'`` Returns: Class or Function ''' assert level in _LEVELS def", "#----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- INTERNAL = 'internal' PUBLIC = 'public' #-----------------------------------------------------------------------------", "Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered", "have attributes: .. code-block:: python __bkversion__ = version __bklevel__ = {internal} Args: version", "or method @wraps(obj) def wrapper(*args, **kw): return obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__", "tuple ``(x,y,z)`` stating what version this object was introduced. Returns: Class or Function", "Returns: bool ''' return obj.__bkversion__ == version def public(version): ''' Declare an object", "codebase in mind, and may not work in general ''' import sys if", "_access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC)) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _LEVELS =", "introduced. Returns: Class or Function ''' return _access(version, 'public') public.__doc__ = format_docstring(public.__doc__, public=repr(PUBLIC))", "how many public/internal things there are declared # in a module so we", "a new one if necessary ''' if not hasattr(mod, '__bkapi__'): mod.__bkapi__ = {PUBLIC:", "Otherwise we are decorating a function or method @wraps(obj) def wrapper(*args, **kw): return", "'public' #----------------------------------------------------------------------------- # Public API #-----------------------------------------------------------------------------o def internal(version): ''' Declare an object to", "Declare an object to be ``{{ level }}``, introduced in ``version``. This generic", "**kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level return wrapper return decorator def _get_module(obj):", "the Bokeh codebase in mind, and may not work in general ''' import", "or property to test Returns: bool ''' return hasattr(obj, '__bklevel__') and hasattr(obj, '__bkversion__')", "obj(*args, **kw) wrapper.__bkversion__ = version wrapper.__bklevel__ = level return wrapper return decorator def", "API #----------------------------------------------------------------------------- _LEVELS = [PUBLIC, INTERNAL] def _access(version, level): ''' Declare an object", "Function ''' assert level in _LEVELS def decorator(obj): # Keep track of how" ]
[ "no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': { 'description': '권한 없음' } } }", "{ 'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) },", "'{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': {", "generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header],", "def generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters':", "app.docs.v2 import jwt_header def generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'], 'description': '{}신청", "'responses': { '200': { 'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를", "정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': { 'description':", "정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': { 'description': '{}신청 정보가 담긴 엑셀", "{ '200': { 'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께", "{ 'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': {", "jwt_header def generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type),", "'200': { 'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type)", "담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': { 'description': '권한", "import jwt_header def generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를", "return { 'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses':", "다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': { 'description': '{}신청 정보가 담긴 엑셀 파일과", "Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': { 'description': '권한 없음' } }", "'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403':", "<filename>Server/app/docs/v2/admin/excel/__init__.py from app.docs.v2 import jwt_header def generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'],", "'tags': ['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200':", "신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': { 'description':", "엑셀 파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': { 'description': '권한 없음'", "정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': { 'description': '{}신청", "파일과 Cache-Control: no-cache 헤더를 함께 응답합니다.'.format(type) }, '403': { 'description': '권한 없음' }", "'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': { 'description': '{}신청 정보가", "'{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': { 'description': '{}신청 정보가 담긴", "[jwt_header], 'responses': { '200': { 'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control: no-cache", "from app.docs.v2 import jwt_header def generate_excel_doc(type): return { 'tags': ['[Admin] 신청 정보'], 'description':", "'parameters': [jwt_header], 'responses': { '200': { 'description': '{}신청 정보가 담긴 엑셀 파일과 Cache-Control:", "['[Admin] 신청 정보'], 'description': '{}신청 정보를 다운로드합니다.'.format(type), 'parameters': [jwt_header], 'responses': { '200': {" ]
[ "import torch import cv2 from skimage.color import rgb2gray from XCSLBP import XCSLBP def", "pixelBlockList: A list contains all element. output_param: featureList: A list contains each element's", "total_ordering import config import numpy as np import copy import torch import cv2", "regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels =", "!= config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features", "for pixel, label in zip(originalImg, labels)] pixelBlock = [pixel if label == i", "= XCS * (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList = [] for i", "def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels", "all element. output_param: featureList: A list contains each element's feature. feature contains 3", "= torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal]", "copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock = np.array([255,", "XCS = XCSLBP(img) XCS = XCS * (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList", "[] for y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any():", "Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A list contains each element's feature. feature", "= torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i in range(numlab +", "GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal,", "# I = rgb2gray(img) XCS = XCSLBP(img) XCS = XCS * (255/ 16)", "i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float())", "pixelBlock. # pixelBlock = [pixel if label == i else blankBlock for pixel,", "label in zip(originalImg, labels)] pixelBlock = [pixel if label == i else config.blankBlock", "grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame = img[:, :, 1]", "in range(numlab + 1): f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal =", "dimentions of input img. np.ndarray labels: label matrix of input img. np.ndarray output_param:", "GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels)", "max(labels) rlabels = labels.view(config.imgSize) # I = rgb2gray(img) XCS = XCSLBP(img) XCS =", "A list contains each element's feature. feature contains 3 channel's mean value. '''", "featureList = [] for i in range(len(pixelBlockList)): pixelList = [] locationList = []", "= range(1, col + 1) y = range(1, row + 1) Sx, Sy", "np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180 / np.pi) Gx, Gy,", "Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i in range(numlab", "input_param: img: img matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A", "0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir", "img. np.ndarray labels: label matrix of input img. np.ndarray output_param: pixelBlockList: a list", "pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list", "1): f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList", "y = range(1, row + 1) Sx, Sy = np.meshgrid(y, x) Sx, Sy", "0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180", "torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i in range(numlab + 1): f =", "colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels", "for y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x]))", "label == i else config.blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock =", "''' input_param: img: img matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList:", "= [pixel if label == i else config.blankBlock for pixel, label in zip(originalImg,", "torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal]", "= textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels '''", "A list contains each element's feature. feature contains 3 channel's mean value and", "= img[:, :, 2] for i in range(numlab + 1): f = torch.eq(rlabels,", "zip(originalImg, labels)] pixelBlock = [pixel if label == i else config.blankBlock for pixel,", "edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize) col, row = config.imgSize", "[redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels):", "torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal,", "contains each element's feature. feature contains 3 channel's mean value. ''' numlab =", ":, 2] for i in range(numlab + 1): f = torch.eq(rlabels, i) graySpLocal", "from skimage.color import rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param:", "config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains", "rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :,", "col, row = config.imgSize x = range(1, col + 1) y = range(1,", "torch.tensor(XCS) textureFeatureList = [] for i in range(numlab + 1): f = torch.eq(rlabels,", "config.imgSize x = range(1, col + 1) y = range(1, row + 1)", "range(numlab + 1): f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float())", "row = config.imgSize x = range(1, col + 1) y = range(1, row", "mean value. ''' numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame", "+ 1) Sx, Sy = np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList", "= torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return", "np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param:", "if label == i else blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock", "numlab = max(labels) rlabels = labels.view(config.imgSize) # frame = rgb2gray(img) Gx = cv2.Sobel(img,", "dimentions of its parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = []", "labels: label matrix of input img. np.ndarray output_param: pixelBlockList: a list contains all", "for i in range(maxLabel + 1): # Uncomment line24 and comment line25 to", "torch.tensor output_param: colorFeatureList: A list contains each element's feature. feature contains 3 channel's", "due to max() function alters dimentions of its parameter newLabels = copy.deepcopy(labels) maxLabel", "cv2 from skimage.color import rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): '''", "blueFrame = img[:, :, 2] for i in range(numlab + 1): f =", "img processing. from functools import total_ordering import config import numpy as np import", "= torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList", "np.arctan2(Gy, Gx) * (180 / np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy),", "torch import cv2 from skimage.color import rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg,", "[] for i in range(numlab + 1): f = torch.eq(rlabels, i) SxSpLocal =", "i in range(maxLabel + 1): # Uncomment line24 and comment line25 to visualize", "cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 +", "extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels matrix that squeezed to 2 dimentions", "''' input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) #", "1) Sx, Sy = np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList =", "textureFeatureList = [] for i in range(numlab + 1): f = torch.eq(rlabels, i)", "edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def", "= torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1)", "= torch.tensor(XCS) textureFeatureList = [] for i in range(numlab + 1): f =", "range(numlab + 1): f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float())", "output_param: pixelBlockList: a list contains all pixelblock which incoporates same label pixels. '''", "channel's mean value and mean position info. ''' featureList = [] for i", "locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList # Optimized version def regionColorFeatures(img, labels):", "each element's feature. feature contains 3 channel's mean value and mean position info.", "Functions of img processing. from functools import total_ordering import config import numpy as", "input img. np.ndarray output_param: pixelBlockList: a list contains all pixelblock which incoporates same", "np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList #", "to 2 dimentions of input img. np.ndarray labels: label matrix of input img.", "* (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList = [] for i in range(numlab", "1): # Uncomment line24 and comment line25 to visualize pixelBlock. # pixelBlock =", "/ np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList =", "torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i in range(numlab + 1): f =", "line24 and comment line25 to visualize pixelBlock. # pixelBlock = [pixel if label", "= copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock =", "pixels matrix that squeezed to 2 dimentions of input img. np.ndarray labels: label", "= np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180 / np.pi) Gx,", "all pixelblock which incoporates same label pixels. ''' # Copy a new labels", "max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for", "= [] for i in range(numlab + 1): f = torch.eq(rlabels, i) XCSSpLocal", "Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag", "edgeFeatureList = [] for i in range(numlab + 1): f = torch.eq(rlabels, i)", "regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels =", "= cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy,", "element's feature. feature contains 3 channel's mean value and mean position info. '''", "(pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0)", "in range(numlab + 1): f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal =", "torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal =", "0] greenFrame = img[:, :, 1] blueFrame = img[:, :, 2] for i", "config import numpy as np import copy import torch import cv2 from skimage.color", "colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread", "range(numlab + 1): f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList =", "matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A list contains each", "locationList = [] for y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x]", "= torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal,", "Original pixels matrix that squeezed to 2 dimentions of input img. np.ndarray labels:", "labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A list contains each element's feature.", "pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList:", "torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab", "import config import numpy as np import copy import torch import cv2 from", "i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float())", "rlabels = labels.view(config.imgSize) # I = rgb2gray(img) XCS = XCSLBP(img) XCS = XCS", "extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains all element. output_param: featureList: A list", "GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab =", "feature. feature contains 3 channel's mean value. ''' numlab = max(labels) rlabels =", "functools import total_ordering import config import numpy as np import copy import torch", "x = range(1, col + 1) y = range(1, row + 1) Sx,", "import copy import torch import cv2 from skimage.color import rgb2gray from XCSLBP import", "greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature)", "for i in range(numlab + 1): f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float())", "[] locationList = [] for y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if", "''' # Copy a new labels due to max() function alters dimentions of", "torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal] spatialFeatureList.append(spatialFeature)", "skimage.color import rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg:", "def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels matrix that squeezed to 2", "blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param:", "input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # I", "= torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal] spatialFeatureList.append(spatialFeature) spatialFeatureList = torch.tensor(spatialFeatureList)", "= labels.view(config.imgSize) col, row = config.imgSize x = range(1, col + 1) y", "locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature)", "255]) for i in range(maxLabel + 1): # Uncomment line24 and comment line25", "col + 1) y = range(1, row + 1) Sx, Sy = np.meshgrid(y,", "np import copy import torch import cv2 from skimage.color import rgb2gray from XCSLBP", "= [] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame = img[:,", "return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab =", "rlabels = labels.view(config.imgSize) # frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0)", "f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float())", "np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = []", "= torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize) col,", "= [] for i in range(numlab + 1): f = torch.eq(rlabels, i) SxSpLocal", "pixelList = [] locationList = [] for y in range(len(pixelBlockList[0])): for x in", "contains each element's feature. feature contains 3 channel's mean value and mean position", "textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab", "torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal,", "return featureList # Optimized version def regionColorFeatures(img, labels): ''' input_param: img: img matrix.", "Gx) * (180 / np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag),", "x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i in range(numlab", "= max(labels) rlabels = labels.view(config.imgSize) # I = rgb2gray(img) XCS = XCSLBP(img) XCS", "XCS = XCS * (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList = [] for", "''' input_param: originalImg: Original pixels matrix that squeezed to 2 dimentions of input", "and comment line25 to visualize pixelBlock. # pixelBlock = [pixel if label ==", "1): f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal =", "XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels matrix that squeezed to", "= np.array([255, 255, 255]) for i in range(maxLabel + 1): # Uncomment line24", "y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y))", "= [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels):", "blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = [pixel if label ==", "list contains each element's feature. feature contains 3 channel's mean value and mean", "max() function alters dimentions of its parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels)", "processing. from functools import total_ordering import config import numpy as np import copy", "torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame = img[:, :, 1] blueFrame =", "= cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag =", "greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): '''", "+ 1): f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal", "frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F,", "of its parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = [] labels", "= range(1, row + 1) Sx, Sy = np.meshgrid(y, x) Sx, Sy =", "for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList),", "2] for i in range(numlab + 1): f = torch.eq(rlabels, i) graySpLocal =", "torch.tensor(Sy) spatialFeatureList = [] for i in range(numlab + 1): f = torch.eq(rlabels,", "def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels", "2 dimentions of input img. np.ndarray labels: label matrix of input img. np.ndarray", "feature. feature contains 3 channel's mean value and mean position info. ''' featureList", "= img[:, :, 0] greenFrame = img[:, :, 1] blueFrame = img[:, :,", "# Functions of img processing. from functools import total_ordering import config import numpy", "torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList", "= torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return", "= max(labels) rlabels = labels.view(config.imgSize) col, row = config.imgSize x = range(1, col", "range(len(pixelBlockList)): pixelList = [] locationList = [] for y in range(len(pixelBlockList[0])): for x", "f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float())", "i in range(numlab + 1): f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal", "1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180 /", "''' numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img))", "= img[:, :, 1] blueFrame = img[:, :, 2] for i in range(numlab", "if label == i else config.blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock", "Sy = np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for", "which incoporates same label pixels. ''' # Copy a new labels due to", "= [] for y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] !=", "torch.tensor labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A list contains each element's", "if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList),", "Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i", "= torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels '''", "= np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList", "its parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = [] labels =", "XCSframe = torch.tensor(XCS) textureFeatureList = [] for i in range(numlab + 1): f", "range(1, col + 1) y = range(1, row + 1) Sx, Sy =", "labels = labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for i in range(maxLabel +", "+ 1): f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList)", "img matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A list contains", "clustering labels. torch.tensor output_param: colorFeatureList: A list contains each element's feature. feature contains", "labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for i in range(maxLabel + 1): #", "img[:, :, 2] for i in range(numlab + 1): f = torch.eq(rlabels, i)", "f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList =", "config.blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0],", "greenFrame = img[:, :, 1] blueFrame = img[:, :, 2] for i in", "maxLabel = max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock = np.array([255, 255,", "labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # frame = rgb2gray(img) Gx", "+ 1): f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature", "textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): '''", "list contains each element's feature. feature contains 3 channel's mean value. ''' numlab", "[] for i in range(numlab + 1): f = torch.eq(rlabels, i) GxSpLocal =", "= torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame = img[:, :, 1] blueFrame", "= max(labels) rlabels = labels.view(config.imgSize) # frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F,", "+ 1) y = range(1, row + 1) Sx, Sy = np.meshgrid(y, x)", "pixel, label in zip(originalImg, labels)] pixelBlock = [pixel if label == i else", "output_param: featureList: A list contains each element's feature. feature contains 3 channel's mean", "torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return", "pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains all element. output_param: featureList:", "+ 1): # Uncomment line24 and comment line25 to visualize pixelBlock. # pixelBlock", "labels)] pixelBlock = [pixel if label == i else config.blankBlock for pixel, label", "output_param: colorFeatureList: A list contains each element's feature. feature contains 3 channel's mean", "rlabels = labels.view(config.imgSize) col, row = config.imgSize x = range(1, col + 1)", "range(1, row + 1) Sx, Sy = np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx),", "i in range(numlab + 1): f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal", "labels): ''' input_param: originalImg: Original pixels matrix that squeezed to 2 dimentions of", "feature contains 3 channel's mean value. ''' numlab = max(labels) rlabels = labels.view(config.imgSize)", "(255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList = [] for i in range(numlab +", "[] labels = labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for i in range(maxLabel", "in range(numlab + 1): f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList", "cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0", "[] for i in range(len(pixelBlockList)): pixelList = [] locationList = [] for y", "[GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab", "mean position info. ''' featureList = [] for i in range(len(pixelBlockList)): pixelList =", "channel's mean value. ''' numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = []", "1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0)", "GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature)", "= [] for i in range(numlab + 1): f = torch.eq(rlabels, i) GxSpLocal", "from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels matrix", "= np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList # Optimized version def", "element. output_param: featureList: A list contains each element's feature. feature contains 3 channel's", "featureList.append(features) featureList = np.array(featureList) return featureList # Optimized version def regionColorFeatures(img, labels): '''", "value. ''' numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame =", "import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels matrix that squeezed", "= [] for i in range(len(pixelBlockList)): pixelList = [] locationList = [] for", "def regionColorFeatures(img, labels): ''' input_param: img: img matrix. torch.tensor labels: Kmeans clustering labels.", "row + 1) Sx, Sy = np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy)", "(180 / np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList", "i in range(len(pixelBlockList)): pixelList = [] locationList = [] for y in range(len(pixelBlockList[0])):", "torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal] spatialFeatureList.append(spatialFeature) spatialFeatureList = torch.tensor(spatialFeatureList) return", "torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i in range(numlab + 1): f", "1] blueFrame = img[:, :, 2] for i in range(numlab + 1): f", "i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList", "redFrame = img[:, :, 0] greenFrame = img[:, :, 1] blueFrame = img[:,", "in range(maxLabel + 1): # Uncomment line24 and comment line25 to visualize pixelBlock.", "img: CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # frame =", "visualize pixelBlock. # pixelBlock = [pixel if label == i else blankBlock for", "pixelBlock = [pixel if label == i else blankBlock for pixel, label in", "alters dimentions of its parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList =", "locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return", "for pixel, label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1],", "colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame =", "i else config.blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock", "np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i in", "return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab =", "Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i in", "incoporates same label pixels. ''' # Copy a new labels due to max()", "pixelblock which incoporates same label pixels. ''' # Copy a new labels due", "i in range(numlab + 1): f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal)", "i else blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = [pixel if", "= torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img,", "torch.tensor(Gdir) edgeFeatureList = [] for i in range(numlab + 1): f = torch.eq(rlabels,", "3 channel's mean value. ''' numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList =", "i in range(numlab + 1): f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal", "in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return", "# frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img,", "= torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature =", "max(labels) rlabels = labels.view(config.imgSize) col, row = config.imgSize x = range(1, col +", "def regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize) col, row = config.imgSize x", "Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i in range(numlab + 1):", "textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels", "labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame", "= np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i", "redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal,", "= XCSLBP(img) XCS = XCS * (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList =", "-1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains all", "featureList = np.array(featureList) return featureList # Optimized version def regionColorFeatures(img, labels): ''' input_param:", "labels due to max() function alters dimentions of its parameter newLabels = copy.deepcopy(labels)", "in range(numlab + 1): f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal =", "''' numlab = max(labels) rlabels = labels.view(config.imgSize) # frame = rgb2gray(img) Gx =", "[pixel if label == i else config.blankBlock for pixel, label in zip(originalImg, labels)]", "featureList: A list contains each element's feature. feature contains 3 channel's mean value", "x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0)", "contains 3 channel's mean value and mean position info. ''' featureList = []", "Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180 / np.pi)", "textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels)", "regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize) col, row = config.imgSize x =", "rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1)", "a new labels due to max() function alters dimentions of its parameter newLabels", "spatialFeatureList = [] for i in range(numlab + 1): f = torch.eq(rlabels, i)", "= rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy = cv2.Sobel(img, cv2.CV_64F, 0,", "== i else blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = [pixel", "img. np.ndarray output_param: pixelBlockList: a list contains all pixelblock which incoporates same label", "contains 3 channel's mean value. ''' numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList", "range(maxLabel + 1): # Uncomment line24 and comment line25 to visualize pixelBlock. #", "np.ndarray labels: label matrix of input img. np.ndarray output_param: pixelBlockList: a list contains", "colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels)", "label pixels. ''' # Copy a new labels due to max() function alters", "originalImg: Original pixels matrix that squeezed to 2 dimentions of input img. np.ndarray", "''' numlab = max(labels) rlabels = labels.view(config.imgSize) # I = rgb2gray(img) XCS =", "featureList # Optimized version def regionColorFeatures(img, labels): ''' input_param: img: img matrix. torch.tensor", "Copy a new labels due to max() function alters dimentions of its parameter", "blankBlock = np.array([255, 255, 255]) for i in range(maxLabel + 1): # Uncomment", "return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize) col, row =", "labels. torch.tensor output_param: colorFeatureList: A list contains each element's feature. feature contains 3", "[] for i in range(numlab + 1): f = torch.eq(rlabels, i) XCSSpLocal =", "else config.blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock =", "torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal]", "def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains all element. output_param: featureList: A", "features = np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList # Optimized version", "label matrix of input img. np.ndarray output_param: pixelBlockList: a list contains all pixelblock", "GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature", "regionColorFeatures(img, labels): ''' input_param: img: img matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor", "input_param: pixelBlockList: A list contains all element. output_param: featureList: A list contains each", "Optimized version def regionColorFeatures(img, labels): ''' input_param: img: img matrix. torch.tensor labels: Kmeans", "torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList =", "config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features =", "img: img matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor output_param: colorFeatureList: A list", "numpy as np import copy import torch import cv2 from skimage.color import rgb2gray", "# Optimized version def regionColorFeatures(img, labels): ''' input_param: img: img matrix. torch.tensor labels:", "edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize)", "label == i else blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock =", "pixelBlock = [pixel if label == i else config.blankBlock for pixel, label in", "= np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): '''", "colorFeatureList: A list contains each element's feature. feature contains 3 channel's mean value.", "rgb2gray(img) XCS = XCSLBP(img) XCS = XCS * (255/ 16) XCSframe = torch.tensor(XCS)", "= [pixel if label == i else blankBlock for pixel, label in zip(originalImg,", "labels.view(config.imgSize) # frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy =", "and mean position info. ''' featureList = [] for i in range(len(pixelBlockList)): pixelList", "# pixelBlock = [pixel if label == i else blankBlock for pixel, label", "img: CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # I =", "matrix of input img. np.ndarray output_param: pixelBlockList: a list contains all pixelblock which", "axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList # Optimized", "= torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal,", "[] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0] greenFrame = img[:, :,", "= [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img,", "== i else config.blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock)", "3 channel's mean value and mean position info. ''' featureList = [] for", "torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels):", "import cv2 from skimage.color import rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels):", "= pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A", "Gy = cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir =", "= [] locationList = [] for y in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])):", "torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img: CV2.imread", "for i in range(numlab + 1): f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float())", "in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature", "for i in range(numlab + 1): f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float())", "= np.arctan2(Gy, Gx) * (180 / np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx),", "zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList", "img[:, :, 1] blueFrame = img[:, :, 2] for i in range(numlab +", "np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList) return featureList # Optimized version def regionColorFeatures(img,", "Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i in range(numlab +", "XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels matrix that", "np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList =", "= max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock = np.array([255, 255, 255])", "labels.view(config.imgSize) col, row = config.imgSize x = range(1, col + 1) y =", "labels): ''' input_param: img: img matrix. torch.tensor labels: Kmeans clustering labels. torch.tensor output_param:", "to visualize pixelBlock. # pixelBlock = [pixel if label == i else blankBlock", "matrix that squeezed to 2 dimentions of input img. np.ndarray labels: label matrix", "np.array([255, 255, 255]) for i in range(maxLabel + 1): # Uncomment line24 and", "labels.view(config.imgSize) # I = rgb2gray(img) XCS = XCSLBP(img) XCS = XCS * (255/", "torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal =", "range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature =", "= torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param: img:", "labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # I = rgb2gray(img) XCS", "in range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature", "of input img. np.ndarray output_param: pixelBlockList: a list contains all pixelblock which incoporates", "for i in range(numlab + 1): f = torch.eq(rlabels, i) XCSSpLocal = torch.mean(XCSframe[f].float())", "1): f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal =", "CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # frame = rgb2gray(img)", "Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180 / np.pi) Gx, Gy, Gmag, Gdir", "torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for i in range(numlab + 1):", "Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir) edgeFeatureList = [] for", "torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels = labels.view(config.imgSize) col, row", "labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def", "''' input_param: pixelBlockList: A list contains all element. output_param: featureList: A list contains", "colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features)", "SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal] spatialFeatureList.append(spatialFeature) spatialFeatureList =", "# Uncomment line24 and comment line25 to visualize pixelBlock. # pixelBlock = [pixel", "input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # frame", "= torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList", "rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original pixels", "import rgb2gray from XCSLBP import XCSLBP def extractPixelBlock(originalImg, labels): ''' input_param: originalImg: Original", "input img. np.ndarray labels: label matrix of input img. np.ndarray output_param: pixelBlockList: a", "1): f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature =", "else blankBlock for pixel, label in zip(originalImg, labels)] pixelBlock = [pixel if label", "= torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature =", "blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList)", "max(labels) rlabels = labels.view(config.imgSize) # frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1,", "graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def regionTextureFeatures(img, labels): ''' input_param: img:", "label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock)", "XCSLBP(img) XCS = XCS * (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList = []", "as np import copy import torch import cv2 from skimage.color import rgb2gray from", "squeezed to 2 dimentions of input img. np.ndarray labels: label matrix of input", "line25 to visualize pixelBlock. # pixelBlock = [pixel if label == i else", "* (180 / np.pi) Gx, Gy, Gmag, Gdir = torch.tensor(Gx), torch.tensor(Gy), torch.tensor(Gmag), torch.tensor(Gdir)", "comment line25 to visualize pixelBlock. # pixelBlock = [pixel if label == i", "np.array(featureList) return featureList # Optimized version def regionColorFeatures(img, labels): ''' input_param: img: img", "numlab = max(labels) rlabels = labels.view(config.imgSize) # I = rgb2gray(img) XCS = XCSLBP(img)", "pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1) pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList):", "function alters dimentions of its parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList", ":, 1] blueFrame = img[:, :, 2] for i in range(numlab + 1):", "= [] labels = labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for i in", "pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature = np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature,", "numlab = max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame", "1) y = range(1, row + 1) Sx, Sy = np.meshgrid(y, x) Sx,", ":, 0] greenFrame = img[:, :, 1] blueFrame = img[:, :, 2] for", "copy import torch import cv2 from skimage.color import rgb2gray from XCSLBP import XCSLBP", "f = torch.eq(rlabels, i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal,", "colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList def", "position info. ''' featureList = [] for i in range(len(pixelBlockList)): pixelList = []", "cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx) *", "contains all pixelblock which incoporates same label pixels. ''' # Copy a new", "= config.imgSize x = range(1, col + 1) y = range(1, row +", "to max() function alters dimentions of its parameter newLabels = copy.deepcopy(labels) maxLabel =", "= labels.view(config.imgSize) # frame = rgb2gray(img) Gx = cv2.Sobel(img, cv2.CV_64F, 1, 0) Gy", "parameter newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1)", "version def regionColorFeatures(img, labels): ''' input_param: img: img matrix. torch.tensor labels: Kmeans clustering", "= labels.view(config.imgSize) # I = rgb2gray(img) XCS = XCSLBP(img) XCS = XCS *", "range(numlab + 1): f = torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float())", "i) SxSpLocal = torch.mean(Sx[f].float()) SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal] spatialFeatureList.append(spatialFeature) spatialFeatureList", "pixels. ''' # Copy a new labels due to max() function alters dimentions", "Sx, Sy = np.meshgrid(y, x) Sx, Sy = torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = []", "XCS * (255/ 16) XCSframe = torch.tensor(XCS) textureFeatureList = [] for i in", "img[:, :, 0] greenFrame = img[:, :, 1] blueFrame = img[:, :, 2]", "mean value and mean position info. ''' featureList = [] for i in", "+ Gy**2.0) Gdir = np.arctan2(Gy, Gx) * (180 / np.pi) Gx, Gy, Gmag,", "= rgb2gray(img) XCS = XCSLBP(img) XCS = XCS * (255/ 16) XCSframe =", "''' featureList = [] for i in range(len(pixelBlockList)): pixelList = [] locationList =", "= torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal", "same label pixels. ''' # Copy a new labels due to max() function", "I = rgb2gray(img) XCS = XCSLBP(img) XCS = XCS * (255/ 16) XCSframe", "GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels", "max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:,", "CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize) # I = rgb2gray(img)", "each element's feature. feature contains 3 channel's mean value. ''' numlab = max(labels)", "= torch.eq(rlabels, i) GxSpLocal = torch.mean(Gx[f].float()) GySpLocal = torch.mean(Gy[f].float()) GmagSpLocal = torch.mean(Gmag[f].float()) GdirSpLocal", "labels): ''' input_param: img: CV2.imread labels ''' numlab = max(labels) rlabels = labels.view(config.imgSize)", "pixel, label in zip(originalImg, labels)] pixelBlock = np.array(pixelBlock) pixelBlock = pixelBlock.reshape(config.imgSize[0], config.imgSize[1], -1)", "range(len(pixelBlockList[0])): for x in range(len(pixelBlockList[1])): if (pixelBlockList[i][y][x] != config.blankBlock).any(): pixelList.append(list(pixelBlockList[i][y][x])) locationList.append((x,y)) colorFeature =", "Gdir = np.arctan2(Gy, Gx) * (180 / np.pi) Gx, Gy, Gmag, Gdir =", "= torch.tensor(Sx), torch.tensor(Sy) spatialFeatureList = [] for i in range(numlab + 1): f", "list contains all element. output_param: featureList: A list contains each element's feature. feature", "textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def regionEdgeFeatures(img, labels): ''' input_param:", "import numpy as np import copy import torch import cv2 from skimage.color import", "255, 255]) for i in range(maxLabel + 1): # Uncomment line24 and comment", "import total_ordering import config import numpy as np import copy import torch import", "in zip(originalImg, labels)] pixelBlock = [pixel if label == i else config.blankBlock for", "[pixel if label == i else blankBlock for pixel, label in zip(originalImg, labels)]", "list contains all pixelblock which incoporates same label pixels. ''' # Copy a", "XCSSpLocal = torch.mean(XCSframe[f].float()) textureFeatureList.append(XCSSpLocal) textureFeatureList = torch.tensor(textureFeatureList) textureFeatureList = textureFeatureList.unsqueeze(1) return textureFeatureList def", "# Copy a new labels due to max() function alters dimentions of its", "pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for i", "axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList = np.array(featureList)", "cv2.Sobel(img, cv2.CV_64F, 0, 1) Gmag = np.sqrt(Gx**2.0 + Gy**2.0) Gdir = np.arctan2(Gy, Gx)", "of input img. np.ndarray labels: label matrix of input img. np.ndarray output_param: pixelBlockList:", "element's feature. feature contains 3 channel's mean value. ''' numlab = max(labels) rlabels", "for i in range(len(pixelBlockList)): pixelList = [] locationList = [] for y in", "pixelBlockList: a list contains all pixelblock which incoporates same label pixels. ''' #", "pixelBlockList.append(pixelBlock) return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains all element.", "from functools import total_ordering import config import numpy as np import copy import", "torch.mean(Gmag[f].float()) GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList =", "A list contains all element. output_param: featureList: A list contains each element's feature.", "that squeezed to 2 dimentions of input img. np.ndarray labels: label matrix of", "Uncomment line24 and comment line25 to visualize pixelBlock. # pixelBlock = [pixel if", "+ 1): f = torch.eq(rlabels, i) graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal", "np.ndarray output_param: pixelBlockList: a list contains all pixelblock which incoporates same label pixels.", "newLabels = copy.deepcopy(labels) maxLabel = max(newLabels) pixelBlockList = [] labels = labels.reshape(-1,1) blankBlock", "return pixelBlockList def extractFeature(pixelBlockList): ''' input_param: pixelBlockList: A list contains all element. output_param:", "= np.array(featureList) return featureList # Optimized version def regionColorFeatures(img, labels): ''' input_param: img:", "16) XCSframe = torch.tensor(XCS) textureFeatureList = [] for i in range(numlab + 1):", "= np.mean(np.array(pixelList), axis=0) locationFeature = np.mean(np.array(locationList), axis=0) features = np.append(colorFeature, locationFeature) featureList.append(features) featureList", "= labels.reshape(-1,1) blankBlock = np.array([255, 255, 255]) for i in range(maxLabel + 1):", "input_param: originalImg: Original pixels matrix that squeezed to 2 dimentions of input img.", "contains all element. output_param: featureList: A list contains each element's feature. feature contains", "feature contains 3 channel's mean value and mean position info. ''' featureList =", "= max(labels) rlabels = labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame =", "value and mean position info. ''' featureList = [] for i in range(len(pixelBlockList)):", "= labels.view(config.imgSize) colorFeatureList = [] grayFrame = torch.tensor(rgb2gray(img)) redFrame = img[:, :, 0]", "graySpLocal = torch.mean(grayFrame[f].float()) redSpLocal = torch.mean(redFrame[f].float()) greenSpLocal = torch.mean(greenFrame[f].float()) blueSpLocal = torch.mean(blueFrame[f].float()) colorFeature", "SySpLocal = torch.mean(Sy[f].float()) spatialFeature = [SxSpLocal, SySpLocal] spatialFeatureList.append(spatialFeature) spatialFeatureList = torch.tensor(spatialFeatureList) return spatialFeatureList", "in range(len(pixelBlockList)): pixelList = [] locationList = [] for y in range(len(pixelBlockList[0])): for", "GdirSpLocal = torch.mean(Gdir[f].float()) edgeFeature = [GxSpLocal, GySpLocal, GmagSpLocal, GdirSpLocal] edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList)", "a list contains all pixelblock which incoporates same label pixels. ''' # Copy", "edgeFeatureList.append(edgeFeature) edgeFeatureList = torch.tensor(edgeFeatureList) return edgeFeatureList def regionSpatialFeatures(labels): numlab = max(labels) rlabels =", "info. ''' featureList = [] for i in range(len(pixelBlockList)): pixelList = [] locationList", "new labels due to max() function alters dimentions of its parameter newLabels =", "numlab = max(labels) rlabels = labels.view(config.imgSize) col, row = config.imgSize x = range(1,", "of img processing. from functools import total_ordering import config import numpy as np", "torch.mean(blueFrame[f].float()) colorFeature = [redSpLocal, greenSpLocal, blueSpLocal, graySpLocal] colorFeatureList.append(colorFeature) colorFeatureList = torch.tensor(colorFeatureList) return colorFeatureList" ]
[ "float values. - direction: direction of the light as an array of three", "KIND, either express or implied. # See the License for the specific language", "LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif lightType == 'Point': light.type = LightUnion.PointLight", "Unless required by applicable law or agreed to in writing, software # distributed", "if intVal < minVal: raise Exception() # Common error handling in except block.", "position of the light as an array of three float values. - direction:", "array of lights to initially populate the light set with. Each member of", "+ str(value) + '\".') def readInt(value, name, minVal): try: intVal = int(value) if", "linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif lightType", "as e: raise Exception('LightSet light doesn\\'t contain element ' + str(e) + '.')", "off based on distance. - quadraticFalloff: amount the light falls off based on", "from DeepSeaScene.Vector3f import CreateVector3f class Object: pass def convertLightSet(convertContext, data): \"\"\" Converts a", "handling in except block. return floatVal except: raise Exception('Invalid ' + name +", "ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight', '')) except KeyError", "set with. Each member of the array has the following members: - name:", "off based on distance. Defaults to 1. - quadraticFalloff: amount the light falls", "on distance. - quadraticFalloff: amount the light falls off based on squared distance.", "members they expect: - \"Directional\" - direction: direction of the light as an", "'\".') def readColor(value, name, srgb): if not isinstance(value, list) or len(value) != 3:", "math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot", "if (minVal is not None and floatVal < minVal) or \\ (maxVal is", "= data.get('srgb', False) lightsData = data.get('lights', []) lights = [] try: for lightData", "+ str(e) + '.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must be", "the name of the main light. If omitted no light will be considered", "max lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb)", "minVal): try: intVal = int(value) if intVal < minVal: raise Exception() # Common", "color of the ambient light as an array of three floats, typically in", "0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight', '')) except KeyError as e: raise", "light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder)", "offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset = 0 if", "on distance. Defaults to 1. - quadraticFalloff: amount the light falls off based", "Defaults to 1. - innerSpotAngle: the angle in degrees of the spot light", "floatVal < minVal) or \\ (maxVal is not None and floatVal > maxVal):", "DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder,", "where it starts to fade out. - outerSpotAngle: the angle in degrees of", "SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0)", "of lights that can be stored. If unset, the number of elements in", "this file except in compliance with the License. # You may obtain a", "(TypeError, ValueError): raise Exception('SceneLights \"lights\" must be an array of objects.') maxLights =", "SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder))", "readVector(value, name): if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight '", "SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder,", "+ ' red channel'), readFloat(value[1], name + ' green channel'), readFloat(value[2], name +", "light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0)", "of the light as an array of three float values. - linearFalloff: amount", "permissions and # limitations under the License. import flatbuffers import math from ..", "be considered the main light. - srgb: true to treat all color values", "\"Spot\" - position: position of the light as an array of three float", "- ambientIntensity: the intensity of the ambient light, which multiplies the color. Defaults", "name, srgb): if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight '", "linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle =", "contain the following elements: - lights: array of lights to initially populate the", "<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "elements: - lights: array of lights to initially populate the light set with.", "'light intensity', 0.0) lightType = lightData['type'] if lightType == 'Directional': light.type = LightUnion.DirectionalLight", "ANY KIND, either express or implied. # See the License for the specific", "light as an array of three float values. - \"Point\" - position: position", "- srgb: true to treat all color values as sRGB values to be", "to all 0. - ambientIntensity: the intensity of the ambient light, which multiplies", "with the members they expect: - \"Directional\" - direction: direction of the light", "import Light from ..LightUnion import LightUnion from .. import PointLight from .. import", "light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type'] if lightType == 'Directional':", "'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light", "from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object: pass def convertLightSet(convertContext,", "scene. The data map is expected to contain the following elements: - lights:", "color. Defaults to 0. - mainLight: the name of the main light. If", "SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0],", "light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2]))", "error handling in except block. return floatVal except: raise Exception('Invalid ' + name", "channel'), readFloat(value[1], name + ' green channel'), readFloat(value[2], name + ' blue channel')]", "+ '.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must be an array", "light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "of three floats, typically in the range [0,1]. Defaults to all 0. -", "srgb) else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight", "spot light where it starts to fade out. - outerSpotAngle: the angle in", "doesn\\'t contain element ' + str(e) + '.') except (AttributeError, TypeError, ValueError): raise", "lightData in lightsData: try: light = Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'],", "it starts to fade out. - outerSpotAngle: the angle in degrees of the", "Defaults to false. \"\"\" def readFloat(value, name, minVal = None, maxVal = None):", "intVal = int(value) if intVal < minVal: raise Exception() # Common error handling", "of the light as an array of three float values. - \"Point\" -", "flatbuffers import math from .. import DirectionalLight from .. import Light from ..LightUnion", "[0,1]. Defaults to all 0. - ambientIntensity: the intensity of the ambient light,", "PointLight from .. import SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f import CreateColor3f", "except (AttributeError, TypeError, ValueError): raise Exception('LightSet must be an object.') builder = flatbuffers.Builder(0)", "!= 3: raise Exception('SceneLight ' + name + ' must be an array", "to 0. - mainLight: the name of the main light. If omitted no", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "angle in degrees of the spot light where it starts to fade out.", "values as sRGB values to be converted to linear space. Defaults to false.", "float values. - \"Point\" - position: position of the light as an array", "'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0),", "of three floats.') color = [readFloat(value[0], name + ' red channel'), readFloat(value[1], name", "= builder.EndVector() else: lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder)", "lightData['type'] if lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction')", "int(value) if intVal < minVal: raise Exception() # Common error handling in except", "light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder,", "lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2]))", "Exception('SceneLight ' + name + ' must be an array of three floats.')", "light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light inner spot angle must be less", "fade out. - maxLights: the maximum number of lights that can be stored.", "nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2]))", "OF ANY KIND, either express or implied. # See the License for the", "data map is expected to contain the following elements: - lights: array of", "' red channel'), readFloat(value[1], name + ' green channel'), readFloat(value[2], name + '", "ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight',", "= lightData['type'] if lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light", "- mainLight: the name of the main light. If omitted no light will", "return [readFloat(value[0], name + ' x'), readFloat(value[1], name + ' y'), readFloat(value[2], name", "light as an array of three float values. - direction: direction of the", "is expected to contain the following elements: - lights: array of lights to", "' y'), readFloat(value[2], name + ' z')] try: srgb = data.get('srgb', False) lightsData", "- color: the color of the light as an array of three float", "color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055, 2.4) return color def readVector(value, name):", "- linearFalloff: amount the light falls off based on distance. - quadraticFalloff: amount", "Exception('SceneLights \"lights\" must be an array of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights',", "' + name + ' must be an array of three floats.') color", "PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder,", "channel'), readFloat(value[2], name + ' blue channel')] if srgb: for i in range(0,", "angle must be less than outer spot angle.') except KeyError as e: raise", "readInt(value, name, minVal): try: intVal = int(value) if intVal < minVal: raise Exception()", "outerSpotAngle: the angle in degrees of the spot light where it finishes fade", "light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light", "the following members: - name: the name of the light. - color: the", "the ambient light, which multiplies the color. Defaults to 0. - mainLight: the", "based on distance. - quadraticFalloff: amount the light falls off based on squared", "Defaults to 0. - mainLight: the name of the main light. If omitted", "must be an array of three floats.') color = [readFloat(value[0], name + '", "not None and floatVal > maxVal): raise Exception() # Common error handling in", "Exception('Invalid ' + name + ' value \"' + str(value) + '\".') def", "+ name + ' must be an array of three floats.') return [readFloat(value[0],", "+ ' y'), readFloat(value[2], name + ' z')] try: srgb = data.get('srgb', False)", "SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle)", "angle.') except KeyError as e: raise Exception('LightSet light doesn\\'t contain element ' +", "x'), readFloat(value[1], name + ' y'), readFloat(value[2], name + ' z')] try: srgb", "import SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object: pass", "name of the light. - color: the color of the light as an", "LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder,", "lights will be used. - ambientColor: the color of the ambient light as", "color def readVector(value, name): if not isinstance(value, list) or len(value) != 3: raise", "import SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import", "cannot have zero max lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData,", "- lights: array of lights to initially populate the light set with. Each", "converted to linear space. Defaults to false. \"\"\" def readFloat(value, name, minVal =", "in degrees of the spot light where it starts to fade out. -", "+ name + ' value \"' + str(value) + '\".') def readColor(value, name,", "= readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic", "the color of the ambient light as an array of three floats, typically", "SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f", "from ..LightUnion import LightUnion from .. import PointLight from .. import SceneLightSet from", "the maximum number of lights that can be stored. If unset, the number", "if lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif", "'.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must be an array of", "the range [0,1]. Defaults to all 0. - ambientIntensity: the intensity of the", "if srgb: for i in range(0, 3): if color[i] <= 0.04045: color[i] =", "raise Exception( 'Spot light inner spot angle must be less than outer spot", "it finishes fade out. - maxLights: the maximum number of lights that can", "e: raise Exception('LightSet doesn\\'t contain element ' + str(e) + '.') except (AttributeError,", "< minVal) or \\ (maxVal is not None and floatVal > maxVal): raise", ".. import SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object:", "1. - \"Spot\" - position: position of the light as an array of", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "float values. - linearFalloff: amount the light falls off based on distance. Defaults", "try: floatVal = float(value) if (minVal is not None and floatVal < minVal)", "considered the main light. - srgb: true to treat all color values as", "are supported with the members they expect: - \"Directional\" - direction: direction of", "the light set with. Each member of the array has the following members:", "array has the following members: - name: the name of the light. -", "== 'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif lightType ==", "= pow((color[i] + 0.055)/1.055, 2.4) return color def readVector(value, name): if not isinstance(value,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'],", "name, minVal = None, maxVal = None): try: floatVal = float(value) if (minVal", "= math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception(", "an array of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights", "'maxLights', 0) if not maxLights and not lights: raise Exception('SceneLights cannot have zero", "str(data.get('mainLight', '')) except KeyError as e: raise Exception('LightSet doesn\\'t contain element ' +", "'.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet must be an object.') builder =", "DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0],", "values to be converted to linear space. Defaults to false. \"\"\" def readFloat(value,", "0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif lightType == 'Spot':", "light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type)", "finishes fade out. - maxLights: the maximum number of lights that can be", "+ ' value \"' + str(value) + '\".') def readInt(value, name, minVal): try:", "the main light. - srgb: true to treat all color values as sRGB", "if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight ' + name", "= DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder,", "DeepSeaScene.Vector3f import CreateVector3f class Object: pass def convertLightSet(convertContext, data): \"\"\" Converts a light", "== 'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff',", "color', srgb) else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0)", "- innerSpotAngle: the angle in degrees of the spot light where it starts", "the light falls off based on squared distance. Defaults to 1. - innerSpotAngle:", "values. - direction: direction of the light as an array of three float", "used. - ambientColor: the color of the ambient light as an array of", "= readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight', '')) except KeyError as", "not lights: raise Exception('SceneLights cannot have zero max lights.') ambientColorData = data.get('ambientColor') if", "e: raise Exception('LightSet light doesn\\'t contain element ' + str(e) + '.') lights.append(light)", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset =", "innerSpotAngle: the angle in degrees of the spot light where it starts to", "intensity', 0.0) mainLight = str(data.get('mainLight', '')) except KeyError as e: raise Exception('LightSet doesn\\'t", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector()", "name + ' must be an array of three floats.') color = [readFloat(value[0],", "supported with the members they expect: - \"Directional\" - direction: direction of the", "= 0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder,", "linearFalloff: amount the light falls off based on distance. - quadraticFalloff: amount the", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light inner spot angle must", "math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0,", "import flatbuffers import math from .. import DirectionalLight from .. import Light from", "following members: - name: the name of the light. - color: the color", "name + ' y'), readFloat(value[2], name + ' z')] try: srgb = data.get('srgb',", "intVal < minVal: raise Exception() # Common error handling in except block. return", "0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer", "lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset", "try: srgb = data.get('srgb', False) lightsData = data.get('lights', []) lights = [] try:", "required by applicable law or agreed to in writing, software # distributed under", "intensity', 0.0) lightType = lightData['type'] if lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction", "'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff',", "= readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff", "falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif lightType ==", "applicable law or agreed to in writing, software # distributed under the License", "as e: raise Exception('LightSet doesn\\'t contain element ' + str(e) + '.') except", "falls off based on distance. Defaults to 1. - quadraticFalloff: amount the light", "str(e) + '.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must be an", "on squared distance. Defaults to 1. - \"Spot\" - position: position of the", "PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder,", "light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot", "CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder)", "Converts a light set for a scene. The data map is expected to", "= readVector(lightData['direction'], 'light direction') elif lightType == 'Point': light.type = LightUnion.PointLight light.position =", "inner spot angle must be less than outer spot angle.') except KeyError as", "except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must be an array of objects.') maxLights", "= math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle',", "or agreed to in writing, software # distributed under the License is distributed", "light falls off based on distance. Defaults to 1. - quadraticFalloff: amount the", "SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object: pass def", "if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb) else: ambientColor = None ambientIntensity", "with. Each member of the array has the following members: - name: the", "Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets):", "following types are supported with the members they expect: - \"Directional\" - direction:", "[readFloat(value[0], name + ' x'), readFloat(value[1], name + ' y'), readFloat(value[2], name +", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif", "readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight', '')) except KeyError as e:", "will be considered the main light. - srgb: true to treat all color", "light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff)", "readColor(value, name, srgb): if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight", "' x'), readFloat(value[1], name + ' y'), readFloat(value[2], name + ' z')] try:", "the range [0, 1]. - intensity: the intensity of the light, which multiplies", "+ '\".') def readColor(value, name, srgb): if not isinstance(value, list) or len(value) !=", "DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object: pass def convertLightSet(convertContext, data):", "readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type']", "falloff', 0.0) elif lightType == 'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light", "the light falls off based on squared distance. Defaults to 1. - \"Spot\"", "Exception('LightSet light doesn\\'t contain element ' + str(e) + '.') lights.append(light) except (TypeError,", "= readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0),", "the light, which multiplies the color. - type: the type of the light.", "maxVal = None): try: floatVal = float(value) if (minVal is not None and", "\\ (maxVal is not None and floatVal > maxVal): raise Exception() # Common", "light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif lightType == 'Point': light.type", "light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder,", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder,", "..LightUnion import LightUnion from .. import PointLight from .. import SceneLightSet from ..", "light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1],", "writing, software # distributed under the License is distributed on an \"AS IS\"", "to initially populate the light set with. Each member of the array has", "lightType = lightData['type'] if lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'],", "in range(0, 3): if color[i] <= 0.04045: color[i] = color[i]/12.92 else: color[i] =", "color. - type: the type of the light. The following types are supported", "'inner spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0))", "' + str(e) + '.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet must be", "light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder)", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "of the light, which multiplies the color. - type: the type of the", "License. # You may obtain a copy of the License at # #", "three float values, typically in the range [0, 1]. - intensity: the intensity", "= color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055, 2.4) return color def readVector(value,", "array of three float values. - direction: direction of the light as an", "raise Exception('SceneLight ' + name + ' must be an array of three", "readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff',", "light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1],", "lights = [] try: for lightData in lightsData: try: light = Object() light.name", "off based on squared distance. Defaults to 1. - \"Spot\" - position: position", "def readInt(value, name, minVal): try: intVal = int(value) if intVal < minVal: raise", "blue channel')] if srgb: for i in range(0, 3): if color[i] <= 0.04045:", "readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff =", "compliance with the License. # You may obtain a copy of the License", "str(value) + '\".') def readInt(value, name, minVal): try: intVal = int(value) if intVal", "must be an array of three floats.') return [readFloat(value[0], name + ' x'),", "3): if color[i] <= 0.04045: color[i] = color[i]/12.92 else: color[i] = pow((color[i] +", "is not None and floatVal > maxVal): raise Exception() # Common error handling", "0.0) lightType = lightData['type'] if lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction =", "language governing permissions and # limitations under the License. import flatbuffers import math", "+ 0.055)/1.055, 2.4) return color def readVector(value, name): if not isinstance(value, list) or", "in lightsData: try: light = Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light", "in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset = 0 if mainLight:", "light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1],", "readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light", "len(value) != 3: raise Exception('SceneLight ' + name + ' must be an", "for the specific language governing permissions and # limitations under the License. import", "ambientColor = readColor(ambientColorData, 'ambient color', srgb) else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity',", "= PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder,", "' value \"' + str(value) + '\".') def readColor(value, name, srgb): if not", "License. import flatbuffers import math from .. import DirectionalLight from .. import Light", "[] try: for lightData in lightsData: try: light = Object() light.name = str(lightData['name'])", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "the light falls off based on distance. Defaults to 1. - quadraticFalloff: amount", "be stored. If unset, the number of elements in lights will be used.", "elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0],", "SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets))", "'\".') def readInt(value, name, minVal): try: intVal = int(value) if intVal < minVal:", "three float values. - direction: direction of the light as an array of", "'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif", "to 1. - \"Spot\" - position: position of the light as an array", "initially populate the light set with. Each member of the array has the", "readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type'] if lightType == 'Directional': light.type =", "array of three float values. - \"Point\" - position: position of the light", "(maxVal is not None and floatVal > maxVal): raise Exception() # Common error", "block. return intVal except: raise Exception('Invalid ' + name + ' value \"'", "lightsData = data.get('lights', []) lights = [] try: for lightData in lightsData: try:", "KeyError as e: raise Exception('LightSet light doesn\\'t contain element ' + str(e) +", "light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder)", "= [] try: for lightData in lightsData: try: light = Object() light.name =", "the License. import flatbuffers import math from .. import DirectionalLight from .. import", "light, which multiplies the color. Defaults to 0. - mainLight: the name of", "if color[i] <= 0.04045: color[i] = color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055,", "squared distance. Defaults to 1. - \"Spot\" - position: position of the light", "= int(value) if intVal < minVal: raise Exception() # Common error handling in", "three floats.') color = [readFloat(value[0], name + ' red channel'), readFloat(value[1], name +", "str(value) + '\".') def readColor(value, name, srgb): if not isinstance(value, list) or len(value)", "not use this file except in compliance with the License. # You may", "y'), readFloat(value[2], name + ' z')] try: srgb = data.get('srgb', False) lightsData =", "= SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder,", "light.position = readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0)", "False) lightsData = data.get('lights', []) lights = [] try: for lightData in lightsData:", "if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else:", "color values as sRGB values to be converted to linear space. Defaults to", "- position: position of the light as an array of three float values.", "light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type ==", "color of the light as an array of three float values, typically in", "readFloat(value[2], name + ' z')] try: srgb = data.get('srgb', False) lightsData = data.get('lights',", "License, Version 2.0 (the \"License\"); # you may not use this file except", "typically in the range [0,1]. Defaults to all 0. - ambientIntensity: the intensity", "color[i] = color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055, 2.4) return color def", "from .. import SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class", "the light falls off based on distance. - quadraticFalloff: amount the light falls", "None and floatVal < minVal) or \\ (maxVal is not None and floatVal", "lightOffsets = [] for light in lights: nameOffset = builder.CreateString(light.name) if light.type ==", "- \"Spot\" - position: position of the light as an array of three", "elements in lights will be used. - ambientColor: the color of the ambient", "will be used. - ambientColor: the color of the ambient light as an", "and floatVal < minVal) or \\ (maxVal is not None and floatVal >", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "values, typically in the range [0, 1]. - intensity: the intensity of the", "off based on squared distance. Defaults to 1. - innerSpotAngle: the angle in", "the light as an array of three float values. - linearFalloff: amount the", "(AttributeError, TypeError, ValueError): raise Exception('LightSet must be an object.') builder = flatbuffers.Builder(0) lightOffsets", "for lightData in lightsData: try: light = Object() light.name = str(lightData['name']) light.color =", "of the spot light where it starts to fade out. - outerSpotAngle: the", "builder = flatbuffers.Builder(0) lightOffsets = [] for light in lights: nameOffset = builder.CreateString(light.name)", "0), 'maxLights', 0) if not maxLights and not lights: raise Exception('SceneLights cannot have", "0.04045: color[i] = color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055, 2.4) return color", "light set with. Each member of the array has the following members: -", "stored. If unset, the number of elements in lights will be used. -", "contain element ' + str(e) + '.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights", "== LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2]))", "= builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if", "SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder,", "180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle:", "# you may not use this file except in compliance with the License.", "false. \"\"\" def readFloat(value, name, minVal = None, maxVal = None): try: floatVal", "maxLights: the maximum number of lights that can be stored. If unset, the", "light.position = readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff',", "agreed to in writing, software # distributed under the License is distributed on", "spot light where it finishes fade out. - maxLights: the maximum number of", "light where it finishes fade out. - maxLights: the maximum number of lights", "of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights and not", "populate the light set with. Each member of the array has the following", "spot angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light inner", "of the ambient light as an array of three floats, typically in the", "less than outer spot angle.') except KeyError as e: raise Exception('LightSet light doesn\\'t", "(the \"License\"); # you may not use this file except in compliance with", "multiplies the color. - type: the type of the light. The following types", "1.0), 'light quadratic falloff', 0.0) elif lightType == 'Spot': light.type = LightUnion.SpotLight light.position", "Object: pass def convertLightSet(convertContext, data): \"\"\" Converts a light set for a scene.", "SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder, ambientIntensity)", ".. import SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f import CreateColor3f from DeepSeaScene.Vector3f", "- quadraticFalloff: amount the light falls off based on squared distance. Defaults to", "be an array of three floats.') color = [readFloat(value[0], name + ' red", "or len(value) != 3: raise Exception('SceneLight ' + name + ' must be", "LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff =", "str(e) + '.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet must be an object.')", "ambient light, which multiplies the color. Defaults to 0. - mainLight: the name", "+ ' blue channel')] if srgb: for i in range(0, 3): if color[i]", "maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder, ambientIntensity) SceneLightSet.AddMainLight(builder,", "import math from .. import DirectionalLight from .. import Light from ..LightUnion import", "# Unless required by applicable law or agreed to in writing, software #", "starts to fade out. - outerSpotAngle: the angle in degrees of the spot", "a scene. The data map is expected to contain the following elements: -", "by applicable law or agreed to in writing, software # distributed under the", "falls off based on squared distance. Defaults to 1. - \"Spot\" - position:", "- outerSpotAngle: the angle in degrees of the spot light where it finishes", "raise Exception() # Common error handling in except block. return intVal except: raise", "name + ' value \"' + str(value) + '\".') def readColor(value, name, srgb):", "builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder,", "SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder,", "Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset", "error handling in except block. return intVal except: raise Exception('Invalid ' + name", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "to fade out. - outerSpotAngle: the angle in degrees of the spot light", "lightType == 'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction =", "falls off based on squared distance. Defaults to 1. - innerSpotAngle: the angle", "' blue channel')] if srgb: for i in range(0, 3): if color[i] <=", "of the spot light where it finishes fade out. - maxLights: the maximum", "of lights to initially populate the light set with. Each member of the", "the light as an array of three float values, typically in the range", "srgb): if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight ' +", "'Spot light inner spot angle must be less than outer spot angle.') except", "= None): try: floatVal = float(value) if (minVal is not None and floatVal", "The following types are supported with the members they expect: - \"Directional\" -", "be used. - ambientColor: the color of the ambient light as an array", "Defaults to all 0. - ambientIntensity: the intensity of the ambient light, which", "squared distance. Defaults to 1. - innerSpotAngle: the angle in degrees of the", "the main light. If omitted no light will be considered the main light.", "light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder,", "srgb: true to treat all color values as sRGB values to be converted", "a light set for a scene. The data map is expected to contain", "the angle in degrees of the spot light where it starts to fade", "float values, typically in the range [0, 1]. - intensity: the intensity of", "the ambient light as an array of three floats, typically in the range", "file except in compliance with the License. # You may obtain a copy", "import CreateVector3f class Object: pass def convertLightSet(convertContext, data): \"\"\" Converts a light set", "of three float values, typically in the range [0, 1]. - intensity: the", "if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light inner spot angle must be", "doesn\\'t contain element ' + str(e) + '.') lights.append(light) except (TypeError, ValueError): raise", "linear space. Defaults to false. \"\"\" def readFloat(value, name, minVal = None, maxVal", "light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light direction')", "CreateVector3f class Object: pass def convertLightSet(convertContext, data): \"\"\" Converts a light set for", "SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder,", "the following elements: - lights: array of lights to initially populate the light", "CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1],", "intVal except: raise Exception('Invalid ' + name + ' value \"' + str(value)", "light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset =", "None, maxVal = None): try: floatVal = float(value) if (minVal is not None", "light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset", "is not None and floatVal < minVal) or \\ (maxVal is not None", "= Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb) light.intensity =", "License for the specific language governing permissions and # limitations under the License.", "range [0, 1]. - intensity: the intensity of the light, which multiplies the", "amount the light falls off based on distance. Defaults to 1. - quadraticFalloff:", "LightUnion from .. import PointLight from .. import SceneLightSet from .. import SpotLight", "mainLight: the name of the main light. If omitted no light will be", "and not lights: raise Exception('SceneLights cannot have zero max lights.') ambientColorData = data.get('ambientColor')", "= readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif lightType == 'Spot': light.type =", "'light quadratic falloff', 0.0) elif lightType == 'Spot': light.type = LightUnion.SpotLight light.position =", "convertLightSet(convertContext, data): \"\"\" Converts a light set for a scene. The data map", "light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light", "SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder)", "to in writing, software # distributed under the License is distributed on an", "+ '\".') def readInt(value, name, minVal): try: intVal = int(value) if intVal <", "readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0,", "0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder,", "srgb: for i in range(0, 3): if color[i] <= 0.04045: color[i] = color[i]/12.92", "implied. # See the License for the specific language governing permissions and #", "data.get('srgb', False) lightsData = data.get('lights', []) lights = [] try: for lightData in", "= readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle',", "\"License\"); # you may not use this file except in compliance with the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "contain element ' + str(e) + '.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet", "must be less than outer spot angle.') except KeyError as e: raise Exception('LightSet", "ambient light as an array of three floats, typically in the range [0,1].", "in degrees of the spot light where it finishes fade out. - maxLights:", "for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset = 0", "values. - \"Point\" - position: position of the light as an array of", "color = [readFloat(value[0], name + ' red channel'), readFloat(value[1], name + ' green", "has the following members: - name: the name of the light. - color:", "readVector(lightData['direction'], 'light direction') elif lightType == 'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'],", "name + ' must be an array of three floats.') return [readFloat(value[0], name", "array of three float values. - linearFalloff: amount the light falls off based", "If omitted no light will be considered the main light. - srgb: true", "Common error handling in except block. return intVal except: raise Exception('Invalid ' +", "Exception('LightSet must be an object.') builder = flatbuffers.Builder(0) lightOffsets = [] for light", "Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset", "block. return floatVal except: raise Exception('Invalid ' + name + ' value \"'", "> maxVal): raise Exception() # Common error handling in except block. return floatVal", "the name of the light. - color: the color of the light as", "0. - mainLight: the name of the main light. If omitted no light", "try: light = Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb)", "be an object.') builder = flatbuffers.Builder(0) lightOffsets = [] for light in lights:", "TypeError, ValueError): raise Exception('LightSet must be an object.') builder = flatbuffers.Builder(0) lightOffsets =", "or implied. # See the License for the specific language governing permissions and", "builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor", "of the light as an array of three float values. - direction: direction", "an array of three floats.') return [readFloat(value[0], name + ' x'), readFloat(value[1], name", "not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight ' + name +", "' + str(e) + '.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must", "def convertLightSet(convertContext, data): \"\"\" Converts a light set for a scene. The data", "number of elements in lights will be used. - ambientColor: the color of", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "as an array of three float values. - direction: direction of the light", "light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset)", "lights that can be stored. If unset, the number of elements in lights", "the intensity of the ambient light, which multiplies the color. Defaults to 0.", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "array of three floats.') return [readFloat(value[0], name + ' x'), readFloat(value[1], name +", "direction of the light as an array of three float values. - linearFalloff:", "in writing, software # distributed under the License is distributed on an \"AS", "the light as an array of three float values. - direction: direction of", "maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights and not lights: raise", "omitted no light will be considered the main light. - srgb: true to", "in lights will be used. - ambientColor: the color of the ambient light", "floats.') color = [readFloat(value[0], name + ' red channel'), readFloat(value[1], name + '", "str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0)", "raise Exception('LightSet doesn\\'t contain element ' + str(e) + '.') except (AttributeError, TypeError,", "< minVal: raise Exception() # Common error handling in except block. return intVal", "under the License. import flatbuffers import math from .. import DirectionalLight from ..", "math from .. import DirectionalLight from .. import Light from ..LightUnion import LightUnion", "= LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff", "= str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity',", "light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle)", "<= 0.04045: color[i] = color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055, 2.4) return", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "name + ' blue channel')] if srgb: for i in range(0, 3): if", "ValueError): raise Exception('LightSet must be an object.') builder = flatbuffers.Builder(0) lightOffsets = []", "red channel'), readFloat(value[1], name + ' green channel'), readFloat(value[2], name + ' blue", "light.direction = readVector(lightData['direction'], 'light direction') elif lightType == 'Point': light.type = LightUnion.PointLight light.position", "2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");", "the number of elements in lights will be used. - ambientColor: the color", "= LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif lightType == 'Point': light.type =", "out. - maxLights: the maximum number of lights that can be stored. If", "# Common error handling in except block. return intVal except: raise Exception('Invalid '", "light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset)", "raise Exception('LightSet must be an object.') builder = flatbuffers.Builder(0) lightOffsets = [] for", "multiplies the color. Defaults to 0. - mainLight: the name of the main", "ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder, ambientIntensity) SceneLightSet.AddMainLight(builder, mainLightOffset) builder.Finish(SceneLightSet.End(builder)) return", "SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder, ambientIntensity) SceneLightSet.AddMainLight(builder, mainLightOffset)", "- linearFalloff: amount the light falls off based on distance. Defaults to 1.", "be converted to linear space. Defaults to false. \"\"\" def readFloat(value, name, minVal", "members: - name: the name of the light. - color: the color of", "DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity)", "the light. The following types are supported with the members they expect: -", "(minVal is not None and floatVal < minVal) or \\ (maxVal is not", "' value \"' + str(value) + '\".') def readInt(value, name, minVal): try: intVal", "0. - ambientIntensity: the intensity of the ambient light, which multiplies the color.", "main light. If omitted no light will be considered the main light. -", "lightsData: try: light = Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light color',", "three floats.') return [readFloat(value[0], name + ' x'), readFloat(value[1], name + ' y'),", "mainLight = str(data.get('mainLight', '')) except KeyError as e: raise Exception('LightSet doesn\\'t contain element", "falls off based on distance. - quadraticFalloff: amount the light falls off based", "DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type ==", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "If unset, the number of elements in lights will be used. - ambientColor:", "+ ' green channel'), readFloat(value[2], name + ' blue channel')] if srgb: for", "def readFloat(value, name, minVal = None, maxVal = None): try: floatVal = float(value)", "you may not use this file except in compliance with the License. #", "no light will be considered the main light. - srgb: true to treat", "KeyError as e: raise Exception('LightSet doesn\\'t contain element ' + str(e) + '.')", "floatVal = float(value) if (minVal is not None and floatVal < minVal) or", "floats, typically in the range [0,1]. Defaults to all 0. - ambientIntensity: the", "light, which multiplies the color. - type: the type of the light. The", "name + ' red channel'), readFloat(value[1], name + ' green channel'), readFloat(value[2], name", "which multiplies the color. - type: the type of the light. The following", "= data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb) else: ambientColor =", "+ '.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet must be an object.') builder", "an array of three float values. - direction: direction of the light as", "of three float values. - linearFalloff: amount the light falls off based on", "light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset", "data.get('lights', []) lights = [] try: for lightData in lightsData: try: light =", "'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle", "mainLightOffset = 0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights)", "light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot", "light where it starts to fade out. - outerSpotAngle: the angle in degrees", "return intVal except: raise Exception('Invalid ' + name + ' value \"' +", "on squared distance. Defaults to 1. - innerSpotAngle: the angle in degrees of", "+ ' z')] try: srgb = data.get('srgb', False) lightsData = data.get('lights', []) lights", "based on squared distance. Defaults to 1. - innerSpotAngle: the angle in degrees", "'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif lightType == 'Point':", "raise Exception('LightSet light doesn\\'t contain element ' + str(e) + '.') lights.append(light) except", "light. - color: the color of the light as an array of three", "raise Exception('SceneLights \"lights\" must be an array of objects.') maxLights = readInt(data.get('maxLights', 0),", "\"lights\" must be an array of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0)", "== LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2]))", "set for a scene. The data map is expected to contain the following", "use this file except in compliance with the License. # You may obtain", "as an array of three float values. - linearFalloff: amount the light falls", "1. - innerSpotAngle: the angle in degrees of the spot light where it", "range [0,1]. Defaults to all 0. - ambientIntensity: the intensity of the ambient", "not None and floatVal < minVal) or \\ (maxVal is not None and", "name + ' x'), readFloat(value[1], name + ' y'), readFloat(value[2], name + '", "'light position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear", "float values. - linearFalloff: amount the light falls off based on distance. -", "flatbuffers.Builder(0) lightOffsets = [] for light in lights: nameOffset = builder.CreateString(light.name) if light.type", "PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset =", "nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in", "light as an array of three float values. - linearFalloff: amount the light", "array of three floats, typically in the range [0,1]. Defaults to all 0.", "readFloat(value, name, minVal = None, maxVal = None): try: floatVal = float(value) if", "readFloat(value[1], name + ' y'), readFloat(value[2], name + ' z')] try: srgb =", "unset, the number of elements in lights will be used. - ambientColor: the", "direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0),", "must be an object.') builder = flatbuffers.Builder(0) lightOffsets = [] for light in", "in except block. return intVal except: raise Exception('Invalid ' + name + '", "+ ' x'), readFloat(value[1], name + ' y'), readFloat(value[2], name + ' z')]", "an array of three floats, typically in the range [0,1]. Defaults to all", "all color values as sRGB values to be converted to linear space. Defaults", "except: raise Exception('Invalid ' + name + ' value \"' + str(value) +", "= None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight', ''))", "out. - outerSpotAngle: the angle in degrees of the spot light where it", "angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "the color. - type: the type of the light. The following types are", "or \\ (maxVal is not None and floatVal > maxVal): raise Exception() #", "minVal: raise Exception() # Common error handling in except block. return intVal except:", "readColor(ambientColorData, 'ambient color', srgb) else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient", "PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder,", "floatVal except: raise Exception('Invalid ' + name + ' value \"' + str(value)", "pass def convertLightSet(convertContext, data): \"\"\" Converts a light set for a scene. The", "based on squared distance. Defaults to 1. - \"Spot\" - position: position of", "raise Exception('SceneLights cannot have zero max lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor", "spot angle.') except KeyError as e: raise Exception('LightSet light doesn\\'t contain element '", "0) if not maxLights and not lights: raise Exception('SceneLights cannot have zero max", "light.color = readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType", "elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0],", "readFloat(value[2], name + ' blue channel')] if srgb: for i in range(0, 3):", "lights: raise Exception('SceneLights cannot have zero max lights.') ambientColorData = data.get('ambientColor') if ambientColorData:", "'')) except KeyError as e: raise Exception('LightSet doesn\\'t contain element ' + str(e)", "space. Defaults to false. \"\"\" def readFloat(value, name, minVal = None, maxVal =", "lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2]))", "of the light. - color: the color of the light as an array", "2.0 (the \"License\"); # you may not use this file except in compliance", "map is expected to contain the following elements: - lights: array of lights", "\"\"\" Converts a light set for a scene. The data map is expected", "array of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights and", "light set for a scene. The data map is expected to contain the", "' z')] try: srgb = data.get('srgb', False) lightsData = data.get('lights', []) lights =", "+ ' must be an array of three floats.') color = [readFloat(value[0], name", "light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if", "'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle", "light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder)", "intensity: the intensity of the light, which multiplies the color. - type: the", "else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight =", "the intensity of the light, which multiplies the color. - type: the type", "light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "lights: nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1],", "class Object: pass def convertLightSet(convertContext, data): \"\"\" Converts a light set for a", "+ name + ' value \"' + str(value) + '\".') def readInt(value, name,", "+ name + ' must be an array of three floats.') color =", "CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder, ambientIntensity) SceneLightSet.AddMainLight(builder, mainLightOffset) builder.Finish(SceneLightSet.End(builder))", "not maxLights and not lights: raise Exception('SceneLights cannot have zero max lights.') ambientColorData", "ambientColor: the color of the ambient light as an array of three floats,", "= readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff", "than outer spot angle.') except KeyError as e: raise Exception('LightSet light doesn\\'t contain", "ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder, ambientIntensity) SceneLightSet.AddMainLight(builder, mainLightOffset) builder.Finish(SceneLightSet.End(builder)) return builder.Output()", "== LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2]))", "an array of three float values. - \"Point\" - position: position of the", "ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb) else: ambientColor", "# # Unless required by applicable law or agreed to in writing, software", "'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff',", "they expect: - \"Directional\" - direction: direction of the light as an array", "an array of three floats.') color = [readFloat(value[0], name + ' red channel'),", "light. If omitted no light will be considered the main light. - srgb:", "express or implied. # See the License for the specific language governing permissions", "except block. return intVal except: raise Exception('Invalid ' + name + ' value", "direction') elif lightType == 'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light position')", "import DirectionalLight from .. import Light from ..LightUnion import LightUnion from .. import", "lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets:", "Each member of the array has the following members: - name: the name", "floats.') return [readFloat(value[0], name + ' x'), readFloat(value[1], name + ' y'), readFloat(value[2],", "0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle >", "of the ambient light, which multiplies the color. Defaults to 0. - mainLight:", "in except block. return floatVal except: raise Exception('Invalid ' + name + '", "for light in lights: nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder,", "light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light", "CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff)", "2.4) return color def readVector(value, name): if not isinstance(value, list) or len(value) !=", "either express or implied. # See the License for the specific language governing", "float(value) if (minVal is not None and floatVal < minVal) or \\ (maxVal", "PointLight.Start(builder) PointLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity)", "angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light inner spot", "Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder, light.type) Light.AddLight(builder, lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for", "the light. - color: the color of the light as an array of", "limitations under the License. import flatbuffers import math from .. import DirectionalLight from", "Light from ..LightUnion import LightUnion from .. import PointLight from .. import SceneLightSet", "quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0)) light.outerSpotAngle =", "position: position of the light as an array of three float values. -", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder,", "Copyright 2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the", "' must be an array of three floats.') return [readFloat(value[0], name + '", "the members they expect: - \"Directional\" - direction: direction of the light as", "light inner spot angle must be less than outer spot angle.') except KeyError", "= None, maxVal = None): try: floatVal = float(value) if (minVal is not", "i in range(0, 3): if color[i] <= 0.04045: color[i] = color[i]/12.92 else: color[i]", "= [] for light in lights: nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight:", "' + name + ' must be an array of three floats.') return", "else: lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset)", "based on distance. Defaults to 1. - quadraticFalloff: amount the light falls off", "light. The following types are supported with the members they expect: - \"Directional\"", "zero max lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color',", "srgb = data.get('srgb', False) lightsData = data.get('lights', []) lights = [] try: for", "def readColor(value, name, srgb): if not isinstance(value, list) or len(value) != 3: raise", "# limitations under the License. import flatbuffers import math from .. import DirectionalLight", "lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset = builder.CreateString(mainLight)", "= readColor(ambientColorData, 'ambient color', srgb) else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0),", "be less than outer spot angle.') except KeyError as e: raise Exception('LightSet light", "amount the light falls off based on squared distance. Defaults to 1. -", "try: intVal = int(value) if intVal < minVal: raise Exception() # Common error", "the License. # You may obtain a copy of the License at #", "lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder,", "\"\"\" def readFloat(value, name, minVal = None, maxVal = None): try: floatVal =", "'light direction') elif lightType == 'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light", "member of the array has the following members: - name: the name of", "[]) lights = [] try: for lightData in lightsData: try: light = Object()", "of three floats.') return [readFloat(value[0], name + ' x'), readFloat(value[1], name + '", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "be an array of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if not", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "+ ' must be an array of three floats.') return [readFloat(value[0], name +", "governing permissions and # limitations under the License. import flatbuffers import math from", "ValueError): raise Exception('SceneLights \"lights\" must be an array of objects.') maxLights = readInt(data.get('maxLights',", "light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1], light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1],", "of the main light. If omitted no light will be considered the main", "except block. return floatVal except: raise Exception('Invalid ' + name + ' value", "of three float values. - \"Point\" - position: position of the light as", "as an array of three floats, typically in the range [0,1]. Defaults to", "pow((color[i] + 0.055)/1.055, 2.4) return color def readVector(value, name): if not isinstance(value, list)", "of three float values. - direction: direction of the light as an array", "1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0)", "'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light", "builder.EndVector() else: lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder,", "floatVal > maxVal): raise Exception() # Common error handling in except block. return", "position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0),", "name: the name of the light. - color: the color of the light", "[0, 1]. - intensity: the intensity of the light, which multiplies the color.", "all 0. - ambientIntensity: the intensity of the ambient light, which multiplies the", "to be converted to linear space. Defaults to false. \"\"\" def readFloat(value, name,", "srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type'] if lightType ==", ".. import DirectionalLight from .. import Light from ..LightUnion import LightUnion from ..", "None and floatVal > maxVal): raise Exception() # Common error handling in except", "lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\" must be an array of objects.')", "element ' + str(e) + '.') lights.append(light) except (TypeError, ValueError): raise Exception('SceneLights \"lights\"", "main light. - srgb: true to treat all color values as sRGB values", "for i in range(0, 3): if color[i] <= 0.04045: color[i] = color[i]/12.92 else:", "DirectionalLight from .. import Light from ..LightUnion import LightUnion from .. import PointLight", "list) or len(value) != 3: raise Exception('SceneLight ' + name + ' must", "CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object: pass def convertLightSet(convertContext, data): \"\"\" Converts", "minVal = None, maxVal = None): try: floatVal = float(value) if (minVal is", "light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder,", "spot angle must be less than outer spot angle.') except KeyError as e:", "the array has the following members: - name: the name of the light.", "amount the light falls off based on distance. - quadraticFalloff: amount the light", "with the License. # You may obtain a copy of the License at", "and # limitations under the License. import flatbuffers import math from .. import", "degrees of the spot light where it starts to fade out. - outerSpotAngle:", "except KeyError as e: raise Exception('LightSet light doesn\\'t contain element ' + str(e)", "value \"' + str(value) + '\".') def readColor(value, name, srgb): if not isinstance(value,", "object.') builder = flatbuffers.Builder(0) lightOffsets = [] for light in lights: nameOffset =", "Exception('LightSet doesn\\'t contain element ' + str(e) + '.') except (AttributeError, TypeError, ValueError):", "light falls off based on squared distance. Defaults to 1. - \"Spot\" -", "light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif lightType == 'Spot': light.type", "linearFalloff: amount the light falls off based on distance. Defaults to 1. -", "light doesn\\'t contain element ' + str(e) + '.') lights.append(light) except (TypeError, ValueError):", "light will be considered the main light. - srgb: true to treat all", "- name: the name of the light. - color: the color of the", "range(0, 3): if color[i] <= 0.04045: color[i] = color[i]/12.92 else: color[i] = pow((color[i]", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "values. - linearFalloff: amount the light falls off based on distance. - quadraticFalloff:", "true to treat all color values as sRGB values to be converted to", "import PointLight from .. import SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f import", "an array of three float values. - linearFalloff: amount the light falls off", "three float values. - linearFalloff: amount the light falls off based on distance.", "readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) elif lightType == 'Spot': light.type = LightUnion.SpotLight", "# Copyright 2020 <NAME> # # Licensed under the Apache License, Version 2.0", "that can be stored. If unset, the number of elements in lights will", "= builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder,", "light in lights: nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder,", "of the light as an array of three float values, typically in the", "fade out. - outerSpotAngle: the angle in degrees of the spot light where", "the spot light where it finishes fade out. - maxLights: the maximum number", "handling in except block. return intVal except: raise Exception('Invalid ' + name +", "name + ' green channel'), readFloat(value[2], name + ' blue channel')] if srgb:", "CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder,", "CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset =", "intensity of the light, which multiplies the color. - type: the type of", "Exception('SceneLights cannot have zero max lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor =", "name of the main light. If omitted no light will be considered the", "- intensity: the intensity of the light, which multiplies the color. - type:", "' + name + ' value \"' + str(value) + '\".') def readColor(value,", "'ambient intensity', 0.0) mainLight = str(data.get('mainLight', '')) except KeyError as e: raise Exception('LightSet", "light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight: PointLight.Start(builder) PointLight.AddPosition(builder,", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type == LightUnion.PointLight:", "to contain the following elements: - lights: array of lights to initially populate", "lightType == 'Directional': light.type = LightUnion.DirectionalLight light.direction = readVector(lightData['direction'], 'light direction') elif lightType", "as an array of three float values, typically in the range [0, 1].", "of the light. The following types are supported with the members they expect:", "- maxLights: the maximum number of lights that can be stored. If unset,", "light.position[2])) SpotLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity)", "data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb) else: ambientColor = None", "be an array of three floats.') return [readFloat(value[0], name + ' x'), readFloat(value[1],", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "the type of the light. The following types are supported with the members", "== 'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction = readVector(lightData['direction'],", "of the array has the following members: - name: the name of the", "name): if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight ' +", "SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else", "0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise Exception( 'Spot light inner spot angle", "import LightUnion from .. import PointLight from .. import SceneLightSet from .. import", "distance. Defaults to 1. - innerSpotAngle: the angle in degrees of the spot", "elif lightType == 'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position') light.direction", "angle in degrees of the spot light where it finishes fade out. -", "maximum number of lights that can be stored. If unset, the number of", "1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner spot angle', 0.0, 180.0))", "+ str(e) + '.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet must be an", "z')] try: srgb = data.get('srgb', False) lightsData = data.get('lights', []) lights = []", "+ ' value \"' + str(value) + '\".') def readColor(value, name, srgb): if", "as sRGB values to be converted to linear space. Defaults to false. \"\"\"", "distance. - quadraticFalloff: amount the light falls off based on squared distance. Defaults", "= [readFloat(value[0], name + ' red channel'), readFloat(value[1], name + ' green channel'),", "expect: - \"Directional\" - direction: direction of the light as an array of", "color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type'] if lightType", "in the range [0, 1]. - intensity: the intensity of the light, which", "\"Point\" - position: position of the light as an array of three float", "None): try: floatVal = float(value) if (minVal is not None and floatVal <", "degrees of the spot light where it finishes fade out. - maxLights: the", "light.position[1], light.position[2])) PointLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff)", "lightUnionOffset) lightOffsets.append(Light.End(builder)) if lightOffsets: SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset =", "in compliance with the License. # You may obtain a copy of the", "must be an array of objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if", "to false. \"\"\" def readFloat(value, name, minVal = None, maxVal = None): try:", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "sRGB values to be converted to linear space. Defaults to false. \"\"\" def", "# Common error handling in except block. return floatVal except: raise Exception('Invalid '", "outer spot angle.') except KeyError as e: raise Exception('LightSet light doesn\\'t contain element", "= str(data.get('mainLight', '')) except KeyError as e: raise Exception('LightSet doesn\\'t contain element '", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "typically in the range [0, 1]. - intensity: the intensity of the light,", "readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff', 0.0) light.quadraticFalloff =", "SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset) Light.AddLightType(builder,", "following elements: - lights: array of lights to initially populate the light set", "= data.get('lights', []) lights = [] try: for lightData in lightsData: try: light", "raise Exception() # Common error handling in except block. return floatVal except: raise", "' green channel'), readFloat(value[2], name + ' blue channel')] if srgb: for i", "elif lightType == 'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff", "PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0],", "See the License for the specific language governing permissions and # limitations under", "can be stored. If unset, the number of elements in lights will be", "Exception() # Common error handling in except block. return floatVal except: raise Exception('Invalid", "maxVal): raise Exception() # Common error handling in except block. return floatVal except:", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"' + str(value) + '\".') def readInt(value, name, minVal): try: intVal = int(value)", "except KeyError as e: raise Exception('LightSet doesn\\'t contain element ' + str(e) +", "= readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type'] if lightType == 'Directional': light.type", "color[i] <= 0.04045: color[i] = color[i]/12.92 else: color[i] = pow((color[i] + 0.055)/1.055, 2.4)", "- type: the type of the light. The following types are supported with", "name, minVal): try: intVal = int(value) if intVal < minVal: raise Exception() #", "as an array of three float values. - \"Point\" - position: position of", "in lights: nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0],", "Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'],", "in the range [0,1]. Defaults to all 0. - ambientIntensity: the intensity of", "\"' + str(value) + '\".') def readColor(value, name, srgb): if not isinstance(value, list)", "distance. Defaults to 1. - quadraticFalloff: amount the light falls off based on", "0.055)/1.055, 2.4) return color def readVector(value, name): if not isinstance(value, list) or len(value)", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "try: for lightData in lightsData: try: light = Object() light.name = str(lightData['name']) light.color", "objects.') maxLights = readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights and not lights:", "array of three floats.') color = [readFloat(value[0], name + ' red channel'), readFloat(value[1],", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", ".. import PointLight from .. import SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f", "array of three float values, typically in the range [0, 1]. - intensity:", "data): \"\"\" Converts a light set for a scene. The data map is", "1. - quadraticFalloff: amount the light falls off based on squared distance. Defaults", "and floatVal > maxVal): raise Exception() # Common error handling in except block.", "' + name + ' value \"' + str(value) + '\".') def readInt(value,", "lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2]) if ambientColor else 0) SceneLightSet.AddAmbientIntensity(builder,", "the spot light where it starts to fade out. - outerSpotAngle: the angle", "raise Exception('Invalid ' + name + ' value \"' + str(value) + '\".')", "if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder) DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0],", "type of the light. The following types are supported with the members they", "distance. Defaults to 1. - \"Spot\" - position: position of the light as", "= LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear", "'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType = lightData['type'] if", "intensity of the ambient light, which multiplies the color. Defaults to 0. -", "where it finishes fade out. - maxLights: the maximum number of lights that", "the light as an array of three float values. - \"Point\" - position:", "DirectionalLight.AddDirection(builder, CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset", "light.outerSpotAngle: raise Exception( 'Spot light inner spot angle must be less than outer", "light.direction[2])) DirectionalLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) DirectionalLight.AddIntensity(builder, light.intensity) lightUnionOffset = DirectionalLight.End(builder) elif light.type", "position') light.direction = readVector(lightData['direction'], 'light direction') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff',", "= float(value) if (minVal is not None and floatVal < minVal) or \\", "reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset", "' must be an array of three floats.') color = [readFloat(value[0], name +", "ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb) else: ambientColor = None ambientIntensity =", "None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity', 0.0) mainLight = str(data.get('mainLight', '')) except", "from .. import SceneLightSet from .. import SpotLight from DeepSeaScene.Color3f import CreateColor3f from", "specific language governing permissions and # limitations under the License. import flatbuffers import", "readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights and not lights: raise Exception('SceneLights cannot", "from .. import DirectionalLight from .. import Light from ..LightUnion import LightUnion from", "light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if light.innerSpotAngle > light.outerSpotAngle: raise", "'ambient color', srgb) else: ambientColor = None ambientIntensity = readFloat(data.get('ambientIntensity', 0.0), 'ambient intensity',", "Common error handling in except block. return floatVal except: raise Exception('Invalid ' +", "to treat all color values as sRGB values to be converted to linear", "Version 2.0 (the \"License\"); # you may not use this file except in", "except in compliance with the License. # You may obtain a copy of", "color[i] = pow((color[i] + 0.055)/1.055, 2.4) return color def readVector(value, name): if not", "an array of three float values, typically in the range [0, 1]. -", "light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight: SpotLight.Start(builder) SpotLight.AddPosition(builder, CreateVector3f(builder, light.position[0], light.position[1],", "name + ' value \"' + str(value) + '\".') def readInt(value, name, minVal):", "light. - srgb: true to treat all color values as sRGB values to", "lightType == 'Point': light.type = LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff =", "mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1], ambientColor[2])", "green channel'), readFloat(value[2], name + ' blue channel')] if srgb: for i in", "= readInt(data.get('maxLights', 0), 'maxLights', 0) if not maxLights and not lights: raise Exception('SceneLights", "0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'], 'inner", "to 1. - innerSpotAngle: the angle in degrees of the spot light where", "the specific language governing permissions and # limitations under the License. import flatbuffers", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "type: the type of the light. The following types are supported with the", "an object.') builder = flatbuffers.Builder(0) lightOffsets = [] for light in lights: nameOffset", "readFloat(value[1], name + ' green channel'), readFloat(value[2], name + ' blue channel')] if", "from .. import Light from ..LightUnion import LightUnion from .. import PointLight from", "color: the color of the light as an array of three float values,", "Exception() # Common error handling in except block. return intVal except: raise Exception('Invalid", "element ' + str(e) + '.') except (AttributeError, TypeError, ValueError): raise Exception('LightSet must", "Exception( 'Spot light inner spot angle must be less than outer spot angle.')", "lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient color', srgb) else:", "if mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0],", "value \"' + str(value) + '\".') def readInt(value, name, minVal): try: intVal =", "the color of the light as an array of three float values, typically", "else: color[i] = pow((color[i] + 0.055)/1.055, 2.4) return color def readVector(value, name): if", "light as an array of three float values, typically in the range [0,", "for a scene. The data map is expected to contain the following elements:", "light falls off based on distance. - quadraticFalloff: amount the light falls off", "values. - linearFalloff: amount the light falls off based on distance. Defaults to", "three floats, typically in the range [0,1]. Defaults to all 0. - ambientIntensity:", "import CreateColor3f from DeepSeaScene.Vector3f import CreateVector3f class Object: pass def convertLightSet(convertContext, data): \"\"\"", ".. import Light from ..LightUnion import LightUnion from .. import PointLight from ..", "mainLight: mainLightOffset = builder.CreateString(mainLight) SceneLightSet.Start(builder) SceneLightSet.AddLights(builder, lightsOffset) SceneLightSet.AddMaxLights(builder, maxLights) SceneLightSet.AddAmbientColor(builder, CreateColor3f(builder, ambientColor[0], ambientColor[1],", "to 1. - quadraticFalloff: amount the light falls off based on squared distance.", "falloff', 0.0) light.quadraticFalloff = readFloat(lightData.get('quadraticFalloff', 1.0), 'light quadratic falloff', 0.0) light.innerSpotAngle = math.radians(readFloat(lightData['innerSpotAngle'],", "of elements in lights will be used. - ambientColor: the color of the", "light.linearFalloff) SpotLight.AddQuadraticFalloff(builder, light.quadraticFalloff) SpotLight.AddInnerSpotAngle(builder, light.innerSpotAngle) SpotLight.AddOuterSpotAngle(builder, light.outerSpotAngle) lightUnionOffset = SpotLight.End(builder) Light.Start(builder) Light.AddName(builder, nameOffset)", "3: raise Exception('SceneLight ' + name + ' must be an array of", "light.color[1], light.color[2])) PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type", "- \"Point\" - position: position of the light as an array of three", "1]. - intensity: the intensity of the light, which multiplies the color. -", "SceneLightSet.StartLightsVector(builder, len(lightOffsets)) for offset in reversed(lightOffsets): builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset", "to linear space. Defaults to false. \"\"\" def readFloat(value, name, minVal = None,", "light as an array of three floats, typically in the range [0,1]. Defaults", "direction of the light as an array of three float values. - \"Point\"", "three float values. - \"Point\" - position: position of the light as an", "quadratic falloff', 0.0) elif lightType == 'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'],", "spot angle', 0.0, 180.0)) light.outerSpotAngle = math.radians(readFloat(lightData['outerSpotAngle'], 'outer spot angle', 0.0, 180.0)) if", "quadraticFalloff: amount the light falls off based on squared distance. Defaults to 1.", "= readColor(lightData['color'], 'light color', srgb) light.intensity = readFloat(lightData['intensity'], 'light intensity', 0.0) lightType =", "from .. import PointLight from .. import SceneLightSet from .. import SpotLight from", "- ambientColor: the color of the ambient light as an array of three", "maxLights and not lights: raise Exception('SceneLights cannot have zero max lights.') ambientColorData =", "light = Object() light.name = str(lightData['name']) light.color = readColor(lightData['color'], 'light color', srgb) light.intensity", "Defaults to 1. - quadraticFalloff: amount the light falls off based on squared", "ambientIntensity: the intensity of the ambient light, which multiplies the color. Defaults to", "channel')] if srgb: for i in range(0, 3): if color[i] <= 0.04045: color[i]", "lights: array of lights to initially populate the light set with. Each member", "> light.outerSpotAngle: raise Exception( 'Spot light inner spot angle must be less than", "lights to initially populate the light set with. Each member of the array", "The data map is expected to contain the following elements: - lights: array", "[] for light in lights: nameOffset = builder.CreateString(light.name) if light.type == LightUnion.DirectionalLight: DirectionalLight.Start(builder)", "position of the light as an array of three float values. - linearFalloff:", "name + ' z')] try: srgb = data.get('srgb', False) lightsData = data.get('lights', [])", "\"Directional\" - direction: direction of the light as an array of three float", "builder.PrependUOffsetTRelative(offset) lightsOffset = builder.EndVector() else: lightsOffset mainLightOffset = 0 if mainLight: mainLightOffset =", "which multiplies the color. Defaults to 0. - mainLight: the name of the", "return floatVal except: raise Exception('Invalid ' + name + ' value \"' +", "def readVector(value, name): if not isinstance(value, list) or len(value) != 3: raise Exception('SceneLight", "have zero max lights.') ambientColorData = data.get('ambientColor') if ambientColorData: ambientColor = readColor(ambientColorData, 'ambient", "if not maxLights and not lights: raise Exception('SceneLights cannot have zero max lights.')", "light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff) SpotLight.AddQuadraticFalloff(builder,", "number of lights that can be stored. If unset, the number of elements", "= flatbuffers.Builder(0) lightOffsets = [] for light in lights: nameOffset = builder.CreateString(light.name) if", "direction: direction of the light as an array of three float values. -", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "return color def readVector(value, name): if not isinstance(value, list) or len(value) != 3:", "0.0) elif lightType == 'Spot': light.type = LightUnion.SpotLight light.position = readVector(lightData['position'], 'light position')", "the angle in degrees of the spot light where it finishes fade out.", "LightUnion.PointLight light.position = readVector(lightData['position'], 'light position') light.linearFalloff = readFloat(lightData.get('linearFalloff', 1.0), 'light linear falloff',", "+ str(value) + '\".') def readColor(value, name, srgb): if not isinstance(value, list) or", "- direction: direction of the light as an array of three float values.", "expected to contain the following elements: - lights: array of lights to initially", "CreateVector3f(builder, light.direction[0], light.direction[1], light.direction[2])) SpotLight.AddColor(builder, CreateColor3f(builder, light.color[0], light.color[1], light.color[2])) SpotLight.AddIntensity(builder, light.intensity) SpotLight.AddLinearFalloff(builder, light.linearFalloff)", "types are supported with the members they expect: - \"Directional\" - direction: direction", "treat all color values as sRGB values to be converted to linear space.", "Defaults to 1. - \"Spot\" - position: position of the light as an", "minVal) or \\ (maxVal is not None and floatVal > maxVal): raise Exception()", "isinstance(value, list) or len(value) != 3: raise Exception('SceneLight ' + name + '", "[readFloat(value[0], name + ' red channel'), readFloat(value[1], name + ' green channel'), readFloat(value[2],", "- \"Directional\" - direction: direction of the light as an array of three", "the color. Defaults to 0. - mainLight: the name of the main light.", "PointLight.AddIntensity(builder, light.intensity) PointLight.AddLinearFalloff(builder, light.linearFalloff) PointLight.AddQuadraticFalloff(builder, light.quadraticFalloff) lightUnionOffset = PointLight.End(builder) elif light.type == LightUnion.SpotLight:", "light falls off based on squared distance. Defaults to 1. - innerSpotAngle: the", "0.0) mainLight = str(data.get('mainLight', '')) except KeyError as e: raise Exception('LightSet doesn\\'t contain" ]
[ "history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in line: yield", "automatically deleted if you add more items than the maxlength allows. You can", "line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for line, prevlines in", "Lets you append and prepend to a list. Faster at finding stuff I", "I guess? It is O(1) of memory use when inserting or popping, but", "deques as lists too. \"\"\" p = deque(maxlen=3) p.append(1) p.append(2) p.append(3) p.append(4) print(p)", "can just use deques as lists too. \"\"\" p = deque(maxlen=3) p.append(1) p.append(2)", "* 20) \"\"\" You don't have to delete items from a deque. They", "with open(\"potato.txt\") as f: for line, prevlines in search(f, \"python\", 3): for pline", "memory use when inserting or popping, but lists are O(N). \"\"\" from collections", "don't have to delete items from a deque. They are automatically deleted if", "search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in", "stuff I guess? It is O(1) of memory use when inserting or popping,", "3): for pline in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\"", "prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\" You don't have to", "maxlength allows. You can just use deques as lists too. \"\"\" p =", "O(1) of memory use when inserting or popping, but lists are O(N). \"\"\"", "just use deques as lists too. \"\"\" p = deque(maxlen=3) p.append(1) p.append(2) p.append(3)", "from a deque. They are automatically deleted if you add more items than", "They are automatically deleted if you add more items than the maxlength allows.", "if you add more items than the maxlength allows. You can just use", "print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\" You don't have to delete", "for line, prevlines in search(f, \"python\", 3): for pline in prevlines: print(pline, end=\"\")", "Faster at finding stuff I guess? It is O(1) of memory use when", "more items than the maxlength allows. You can just use deques as lists", "20) \"\"\" You don't have to delete items from a deque. They are", "in line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for line, prevlines", "from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line", "prevlines in search(f, \"python\", 3): for pline in prevlines: print(pline, end=\"\") print(line, end=\"\")", "yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for line, prevlines in search(f,", "previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for line, prevlines in search(f, \"python\", 3):", "\"\"\" You don't have to delete items from a deque. They are automatically", "list. Faster at finding stuff I guess? It is O(1) of memory use", "deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if", "for pline in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\" You", "are automatically deleted if you add more items than the maxlength allows. You", "you append and prepend to a list. Faster at finding stuff I guess?", "deque. They are automatically deleted if you add more items than the maxlength", "items from a deque. They are automatically deleted if you add more items", "O(N). \"\"\" from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history)", "as lists too. \"\"\" p = deque(maxlen=3) p.append(1) p.append(2) p.append(3) p.append(4) print(p) p.appendleft(5)", "pattern in line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for line,", "than the maxlength allows. You can just use deques as lists too. \"\"\"", "add more items than the maxlength allows. You can just use deques as", "or popping, but lists are O(N). \"\"\" from collections import deque def search(lines,", "lists too. \"\"\" p = deque(maxlen=3) p.append(1) p.append(2) p.append(3) p.append(4) print(p) p.appendleft(5) print(p)", "of memory use when inserting or popping, but lists are O(N). \"\"\" from", "deque(maxlen=history) for line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line)", "is O(1) of memory use when inserting or popping, but lists are O(N).", "previous_lines.append(line) with open(\"potato.txt\") as f: for line, prevlines in search(f, \"python\", 3): for", "to delete items from a deque. They are automatically deleted if you add", "Deque is double-ended-queue. Lets you append and prepend to a list. Faster at", "\"\"\" from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for", "is double-ended-queue. Lets you append and prepend to a list. Faster at finding", "It is O(1) of memory use when inserting or popping, but lists are", "lines: if pattern in line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f:", "line, prevlines in search(f, \"python\", 3): for pline in prevlines: print(pline, end=\"\") print(line,", "in search(f, \"python\", 3): for pline in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\"", "print(line, end=\"\") print(\"-\" * 20) \"\"\" You don't have to delete items from", "inserting or popping, but lists are O(N). \"\"\" from collections import deque def", "print(\"-\" * 20) \"\"\" You don't have to delete items from a deque.", "a deque. They are automatically deleted if you add more items than the", "for line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line) with", "lists are O(N). \"\"\" from collections import deque def search(lines, pattern, history=5): previous_lines", "at finding stuff I guess? It is O(1) of memory use when inserting", "You don't have to delete items from a deque. They are automatically deleted", "when inserting or popping, but lists are O(N). \"\"\" from collections import deque", "guess? It is O(1) of memory use when inserting or popping, but lists", "pline in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\" You don't", "def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern", "import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines:", "f: for line, prevlines in search(f, \"python\", 3): for pline in prevlines: print(pline,", "items than the maxlength allows. You can just use deques as lists too.", "open(\"potato.txt\") as f: for line, prevlines in search(f, \"python\", 3): for pline in", "collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in", "double-ended-queue. Lets you append and prepend to a list. Faster at finding stuff", "previous_lines = deque(maxlen=history) for line in lines: if pattern in line: yield line,", "you add more items than the maxlength allows. You can just use deques", "but lists are O(N). \"\"\" from collections import deque def search(lines, pattern, history=5):", "to a list. Faster at finding stuff I guess? It is O(1) of", "in lines: if pattern in line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as", "finding stuff I guess? It is O(1) of memory use when inserting or", "line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\")", "pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in line:", "if pattern in line: yield line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for", "are O(N). \"\"\" from collections import deque def search(lines, pattern, history=5): previous_lines =", "have to delete items from a deque. They are automatically deleted if you", "end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\" You don't have to delete items", "allows. You can just use deques as lists too. \"\"\" p = deque(maxlen=3)", "append and prepend to a list. Faster at finding stuff I guess? It", "in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20) \"\"\" You don't have", "\"python\", 3): for pline in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" * 20)", "You can just use deques as lists too. \"\"\" p = deque(maxlen=3) p.append(1)", "popping, but lists are O(N). \"\"\" from collections import deque def search(lines, pattern,", "a list. Faster at finding stuff I guess? It is O(1) of memory", "as f: for line, prevlines in search(f, \"python\", 3): for pline in prevlines:", "end=\"\") print(\"-\" * 20) \"\"\" You don't have to delete items from a", "delete items from a deque. They are automatically deleted if you add more", "prepend to a list. Faster at finding stuff I guess? It is O(1)", "and prepend to a list. Faster at finding stuff I guess? It is", "search(f, \"python\", 3): for pline in prevlines: print(pline, end=\"\") print(line, end=\"\") print(\"-\" *", "use when inserting or popping, but lists are O(N). \"\"\" from collections import", "use deques as lists too. \"\"\" p = deque(maxlen=3) p.append(1) p.append(2) p.append(3) p.append(4)", "deleted if you add more items than the maxlength allows. You can just", "\"\"\" Deque is double-ended-queue. Lets you append and prepend to a list. Faster", "= deque(maxlen=history) for line in lines: if pattern in line: yield line, previous_lines", "line, previous_lines previous_lines.append(line) with open(\"potato.txt\") as f: for line, prevlines in search(f, \"python\",", "the maxlength allows. You can just use deques as lists too. \"\"\" p" ]
[ "import numpy as np import matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors import", "\", Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1)", "3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs", "how many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples", "dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue)))", "sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis", "dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i]))))", "features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values=", "stats import p_value_scoring_object import numpy as np import matplotlib.pyplot as plt import numpy.matlib", "print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__:", "data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file", "print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and division Scp2 =", "+ \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]:", "dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\")", "no_1=features_1.shape[0] #Give all samples in file 0 the label 0 and in file", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs 9", "#print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with", "\",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and division Scp2", "setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width))", ": \", Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0)", "numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing", "vectors corresponding to features and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os", "= np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for", "the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in each sample", "import Normalize import matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing import StandardScaler ##############################################################################", "print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont,", "4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[]", "X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in", "{0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i]))))", "wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2)", "It takes input files with column vectors corresponding to features and lables. \"\"\"", "contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods", "in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from", "with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t',", "\\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1)", "to features and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os from scipy", "#print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1)", "print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof)", "no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1]", "Sine with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 =", "as np import matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors import Normalize import", "setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\"", "print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof *= no_bins[1] dof-=1", "name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] #", "#Make 6.0-1.0=5 ticks between the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))", "max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of bins per axis\") ax1.set_ylabel(\"pvalue\") ax1.set_title(name)", "6.0-1.0=5 ticks between the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number", "= np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim in range(1,no_dim):", "#x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim]", "exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) :", "10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D", "ticks between the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs 99th", "X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0", "= data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min", "min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of bins per axis\")", "setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width))", "no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0 the label 0 and in", "and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os from scipy import stats", "as plt import numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker as mtick import", "exec setup_command_0 exec setup_command_1 for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:]))", "= (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim):", "############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[]", "boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0", "plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5", "in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0 the label", "as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig=", "dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1", "are Not A Number (NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 : \",", "legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4", "= csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1)", "dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0", "Scp2) #nansum ignores all the contributions that are Not A Number (NAN) Chi2", "range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0):", "(=chi squared). It takes input files with column vectors corresponding to features and", "be used to get the p value for the Miranda method (=chi squared).", "sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")]", "#print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else:", "#if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in range(no_dim):", "containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim", "# Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz", "#Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1", "polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions", "print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and", "expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\")", "legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4", "1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features.", "label 0 and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an", "np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins))", "#bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec", "StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35]", "setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\"", "if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for", "# gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")]", "9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")]", "single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data", "{0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats", "in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples", "np import matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker", "contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list)", "ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min and", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ##############################################################################", "writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2])", "10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for", "samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data)", "subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2) #nansum", "for the Miranda method (=chi squared). It takes input files with column vectors", "numpy as np import matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors import Normalize", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs 99th legendre polynomial", "for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]:", "Miranda method (=chi squared). It takes input files with column vectors corresponding to", "and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2) #nansum ignores", "= \"bins_sample1[\" for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\"", "#eliminate boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1", "str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 +", "+= str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i in range(no_0+no_1): #bin", "input files with column vectors corresponding to features and lables. \"\"\" print(__doc__) import", "str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i in", "sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed =", "\"bins_sample1[\" for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\"", ": \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0))", "+= str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0", "print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element", "method (=chi squared). It takes input files with column vectors corresponding to features", "p_value_scoring_object import numpy as np import matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors", "from scipy import stats import p_value_scoring_object import numpy as np import matplotlib.pyplot as", ": \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as test_statistics_file:", "1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the", "= \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1", "+ \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1", "features and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os from scipy import", "no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of bins per axis\") ax1.set_ylabel(\"pvalue\") ax1.set_title(name) fig.savefig(name+\"_plot.png\")", "#print(pos_bins) #eliminate boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0]", "if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) :", "= np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2) #nansum ignores all the contributions", "bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec", "data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max", "__debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1))", "\", Scp2) #nansum ignores all the contributions that are Not A Number (NAN)", "#legendreSquared one contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")]", "*= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue", "+=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1", "\"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 +=", "100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one", "score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer", "many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in", "matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\"", ": {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()])", "in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec", "no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue :", "= comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\"", "Not A Number (NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2)", "matplotlib.colors import Normalize import matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing import StandardScaler", "import os from scipy import stats import p_value_scoring_object import numpy as np import", "\"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 +=", "setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i in range(no_0+no_1):", "Number (NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for", ": \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise", "for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects", "np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim", "dof=no_bins[0] for dim in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof :", "dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof)", "the p value for the Miranda method (=chi squared). It takes input files", ":\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data", "{0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1)", "\\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1,", "Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")]", "#extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are", "str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1", "in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0)", "100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th legendre", "data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 =", "matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker as mtick", "bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\"", "\"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 :", "np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2) #nansum ignores all the contributions that", "#Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs", "for dim in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof)))", "= np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1", "X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\"", "Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2) #nansum ignores all the", "expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue)", "get the p value for the Miranda method (=chi squared). It takes input", "for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\"", "data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in", "import sys sys.path.insert(0,'../..') import os from scipy import stats import p_value_scoring_object import numpy", "delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log')", "pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim", "ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks", "pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]):", "sys sys.path.insert(0,'../..') import os from scipy import stats import p_value_scoring_object import numpy as", "# Sine with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1", "############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of", "open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n')", "i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for", ": \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and division", "{0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0", "csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file,", "range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\"", "import matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\"", "print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof", "bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\"", ": \", Scp2) #nansum ignores all the contributions that are Not A Number", "p value for the Miranda method (=chi squared). It takes input files with", "\"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list))", "__debug__: print(\"Scp2 : \", Scp2) #nansum ignores all the contributions that are Not", "label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D", "the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of bins per", "points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0", "an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins", "+= str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i", "-=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in range(no_dim): bin_command_0 +=", ": {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import", "from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed", "periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins", "in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 =", "p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\",", "\"\"\" This script can be used to get the p value for the", "#Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs 99th legendre", "Normalize import matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## #", "polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions", "plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list)", "ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min and max no_ticks=5.0 ticks_list=", "script can be used to get the p value for the Miranda method", "contributions that are Not A Number (NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2", "one contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs", "and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1]", "features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give", "dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue", "one contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4", "with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0]", "[single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width =", "-=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in", "#import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) :", ": \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont,", "periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins", "(NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim", "A Number (NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0]", "print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files", "the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0]", "#y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1", "#Give all samples in file 0 the label 0 and in file 1", "takes input files with column vectors corresponding to features and lables. \"\"\" print(__doc__)", "print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins)", "single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution,", "writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o')", "import p_value_scoring_object import numpy as np import matplotlib.pyplot as plt import numpy.matlib from", "print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine", "= stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import", "comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one", "pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont,", "#4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")]", "X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\"", "range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim in", "the contributions that are Not A Number (NAN) Chi2 = np.nansum(Scp2) if __debug__:", ": \",np.sum(bins_sample1)) #element wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2", "1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min", "test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1=", "plt import numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker as mtick import matplotlib", "data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max =", "squared). It takes input files with column vectors corresponding to features and lables.", "#bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim in range(no_dim):", "print(\"Scp2 : \", Scp2) #nansum ignores all the contributions that are Not A", "- stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont,", "print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof :", "shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre", "setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for", "import StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100", "#print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]:", "if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof *=", "are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0 the", "single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the", "file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and", "import matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## # Setting", "\"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points", "csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1)", "between the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of bins", "print(__doc__) import sys sys.path.insert(0,'../..') import os from scipy import stats import p_value_scoring_object import", "array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins =", "setup_command_1 for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary", "fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make", "comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th", "= \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1", "\",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0)) print(\"bins_sample1 : \",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction", "column vectors corresponding to features and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import", "else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 :", "1 - stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont,", "can be used to get the p value for the Miranda method (=chi", ": \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d')", "in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1", "to get the p value for the Miranda method (=chi squared). It takes", "range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1", "1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1]", "#print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 +=", "#print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1", "\",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)", "= 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")] # gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre", "\",bins_sample1) print(\"np.sum(bins_sample1) : \",np.sum(bins_sample1)) #element wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if", "that are Not A Number (NAN) Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 :", "#element wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \",", "the label 0 and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create", "\"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\"", "as mtick import matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters #", "#4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10", "contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] #", "bin_command_1 = \"bins_sample1[\" for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\"", "scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont,", "#4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")]", "data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min =", "__debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof *= no_bins[1]", "and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing", "lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1])", "# name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.0_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high10Dgauss_optimisation_10000_0.5_0.1_0.01_1.txt\")]", "import numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker as mtick import matplotlib from", "score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating", "file 0 the label 0 and in file 1 the feature 1 label_0=np.zeros((no_0,1))", "files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many", "vs 9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in", "{0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont,", "from matplotlib.colors import Normalize import matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing import", "if __debug__: print(\"Scp2 : \", Scp2) #nansum ignores all the contributions that are", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with", "1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\", os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine", "gaussian_same_projection_on_each_axis comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.1_1.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_2D_1000_0.6_0.2_0.05_1.txt\")] #Legendre #legendre one contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared", "for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts", "used to get the p value for the Miranda method (=chi squared). It", "mtick import matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\"", "exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 +", "sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0 the label 0 and", "data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim = data.shape[1]-1 no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1]", "stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv", "fig.add_subplot(1, 1, 1) ax1.plot(single_no_bins_list,score_list,'o') print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between", "setup_command_0 exec setup_command_1 for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins)", "#bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0)", "os from scipy import stats import p_value_scoring_object import numpy as np import matplotlib.pyplot", "This script can be used to get the p value for the Miranda", "(np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 = \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0", "#nansum ignores all the contributions that are Not A Number (NAN) Chi2 =", "features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0]", "bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in range(no_dim): bin_command_0 += str(int(pos_bins[dim]))+\",\"", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins :", "\"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os from scipy import stats import p_value_scoring_object", "#print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__:", "test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure()", "+= str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin]", "range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue= 1 -", "in file 0 the label 0 and in file 1 the feature 1", "feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1]", "sys.path.insert(0,'../..') import os from scipy import stats import p_value_scoring_object import numpy as np", "samples in file 0 the label 0 and in file 1 the feature", "import stats import p_value_scoring_object import numpy as np import matplotlib.pyplot as plt import", "comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1)", "from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in each", "<filename>Dalitz_simplified/optimisation/miranda/miranda_eval.py<gh_stars>0 \"\"\" This script can be used to get the p value for", "print(\"single_no_bins_list[0]-0.1\",single_no_bins_list[0]-0.1) print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min and max", "position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]):", "np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof", "bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0) : \",np.sum(bins_sample0))", "import matplotlib.pyplot as plt import numpy.matlib from matplotlib.colors import Normalize import matplotlib.ticker as", "matplotlib.ticker as mtick import matplotlib from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters", "import csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t pvalue \\n\") writer =", "comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list: print(\"single_no_bins : \",single_no_bins) print(\"Operating of files", "and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list) ax1.set_yticks(ticks_list) ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax1.set_xlabel(\"number of bins per axis\") ax1.set_ylabel(\"pvalue\")", "corresponding to features and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os from", "vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions 3D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_5__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\",", "with column vectors corresponding to features and lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..')", "+=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if __debug__: print(\"bins_sample0 : \",bins_sample0) print(\"np.sum(bins_sample0)", "print(\"single_no_bins_list[-1]+0.1\",single_no_bins_list[-1]+0.1) ax1.set_yscale('log') plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min and max no_ticks=5.0", "all samples in file 0 the label 0 and in file 1 the", "in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate boundary effects for dim", "plt.xlim([single_no_bins_list[0]-0.1,single_no_bins_list[-1]+0.1]) plt.ylim([min(score_list)*0.8,max(score_list)*1.2]) #Make 6.0-1.0=5 ticks between the min and max no_ticks=5.0 ticks_list= np.power(min(score_list)/max(score_list),(np.arange(no_ticks+1.0))/no_ticks)*max(score_list)", "contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th", "\"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i]))))", "np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width) setup_command_0 = \"bins_sample0=np.zeros((\" setup_command_1 =", "ignores all the contributions that are Not A Number (NAN) Chi2 = np.nansum(Scp2)", "bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0)", "\",single_no_bins) print(\"Operating of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d')", "of files :\"+comp_file_0+\" \"+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how", "99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")]", "= \"bins_sample1=np.zeros((\" for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\"", "each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0 the label 0", "#eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin] +=1 exec bin_command_1 + \"+=1\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) if", "vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th legendre polynomial", "#legendre one contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th", "parameters # name=\"gaussian_same_projection_on_each_axis_0_1vs0_05_optimisation_miranda\" sample1_name=\"particle\" sample2_name=\"antiparticle\" shuffling_seed = 100 single_no_bins_list=[2,3,4,5,6,7,8,9,10,11,12,15,17,20,22,25,27,30,35] comp_file_list=[] #Dalitz #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.0.0.txt\",os.environ['MLToolsDir']+\"/Dalitz/dpmodel/data/data_optimisation.200.1.txt\")] #Gaussian", "stats.chi2.cdf(Chi2,dof) print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont", "contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_5__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__contrib1__0_0__1_0__contrib2__2_0__2_0__contrib3__0_7__3_0__sample_0.txt\")] #4 contributions", "files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in each sample no_0=features_0.shape[0]", "= [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width", "dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont))", "files with column vectors corresponding to features and lables. \"\"\" print(__doc__) import sys", "#chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont,", "\",np.sum(bins_sample1)) #element wise subtraction and division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 :", "pvalue \\n\") writer = csv.writer(test_statistics_file, delimiter='\\t', lineterminator='\\n') writer.writerows(zip(single_no_bins_list,score_list)) fig= plt.figure() ax1= fig.add_subplot(1, 1,", "Chi2 = np.nansum(Scp2) if __debug__: print(\"Chi2 : \", Chi2) dof=no_bins[0] for dim in", "p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins \\t", "#Legendre #legendre one contribution, 100th vs 99th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution,", "0 the label 0 and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1))", "no_bins = [single_no_bins]*no_dim np.random.shuffle(data) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1]", "os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__contrib1__0_0__1_0__2_0__3_0__contrib2__2_0__2_0__3_0__0_0__contrib3__0_7__3_0__0_0__1_0__sample_0.txt\")] #4 contributions 4D #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_5__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1_0__0_0__1_0__2_0__3_0__contrib1__0_0__1_0__2_0__3_0__0_0__contrib2__2_0__2_0__3_0__0_0__1_0__contrib3__0_7__3_0__0_0__1_0__2_0__sample_0.txt\")] # Sine with 10 periods vs 9 periods", "Chi2) dof=no_bins[0] for dim in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof", "all the contributions that are Not A Number (NAN) Chi2 = np.nansum(Scp2) if", "division Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if __debug__: print(\"Scp2 : \", Scp2) #nansum ignores all", "0 and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array", "#comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__100__sample_1.txt\")] #legendreSquared one contribution, 10th vs 9th legendre polynomial #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__10__sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_squared_contrib0__1__9__sample_0.txt\")] #4 contributions 1D", "effects for dim in range(no_dim): if(pos_bins[dim]==no_bins[dim]): pos_bins[dim] -=1 #if(pos_bins[0]==no_bins[0]): #pos_bins[0] -=1 bin_command_0 =", "str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec setup_command_0 exec setup_command_1 for i in range(no_0+no_1): #bin position", "\",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as test_statistics_file: test_statistics_file.write(\"nbins", "p_sp_cont, dof_sp_cont, expected_sp_cont = stats.chi2_contingency([bins_sample1.flatten(),bins_sample0.flatten()]) #print(\"(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont,", "scipy import stats import p_value_scoring_object import numpy as np import matplotlib.pyplot as plt", "lables. \"\"\" print(__doc__) import sys sys.path.insert(0,'../..') import os from scipy import stats import", "the Miranda method (=chi squared). It takes input files with column vectors corresponding", "#determine how many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all", "#pos_bins[0] -=1 bin_command_0 = \"bins_sample0[\" bin_command_1 = \"bins_sample1[\" for dim in range(no_dim): bin_command_0", "label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] no_dim =", "print(\"pvalue : {0}\".format(str(pvalue))) print(\"dof : \",dof) #import scipy.stats #chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont =", "value for the Miranda method (=chi squared). It takes input files with column", "for dim in range(no_dim): setup_command_0 += str(int(no_bins[dim]))+\",\" setup_command_1 += str(int(no_bins[dim]))+\",\" setup_command_0=setup_command_0[:-1]+\"))\" setup_command_1=setup_command_1[:-1]+\"))\" exec", "exec setup_command_1 for i in range(no_0+no_1): #bin position #x_bin=int(np.floor((Xx_values[i]-Xx_min)/Xx_width)) #y_bin=int(np.floor((Xy_values[i]-Xy_min)/Xy_width)) pos_bins=np.floor(np.divide(np.subtract(X_values[i,:],X_min[:]),X_width[:])) #print(pos_bins) #eliminate", "labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_width = (np.divide(np.subtract(X_max,X_min),no_bins)) #print(X_width)", "dim in range(1,no_dim): dof *= no_bins[1] dof-=1 print(bins_sample0) print(bins_sample1) print(\"Chi2/dof : {0}\".format(str(Chi2/dof))) pvalue=", "bin_command_0 += str(int(pos_bins[dim]))+\",\" bin_command_1 += str(int(pos_bins[dim]))+\",\" bin_command_0=bin_command_0[:-1]+\"]\" bin_command_1=bin_command_1[:-1]+\"]\" #print(\"labels[i]: {0}\".format(str(int(labels[i])))) #print(bin_command_0) if(labels[i]==0): #print(bin_command_0)", "if(labels[i]==0): #print(bin_command_0) #bins_sample0[y_bin,x_bin] +=1 exec bin_command_0 + \"+=1\" #eval(bin_command_0) #print(\"labels[i]: {0}\".format(str(int(labels[i])))) else: #bins_sample1[y_bin,x_bin]", "expected_sp_cont) : \",(chi2_sp_cont, p_sp_cont, dof_sp_cont, expected_sp_cont)) score_list.append(pvalue) import csv with open(name+\"_values\", \"wb\") as", "9 periods #comp_file_list=[(os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_10_periods_1D_sample_0.txt\",os.environ['MLToolsDir']+\"/Dalitz/gaussian_samples/legendre/legendre_data/data_sin_9_periods_1D_sample_0.txt\")] print(comp_file_list) score_list=[] ############################################################################## comp_file_0,comp_file_1 = comp_file_list[0] for single_no_bins in single_no_bins_list:" ]
[]
[ "actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Defines the marker start/end use.", "@CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available wranglers and test cases.", "pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance =", "actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\",", "correct valid iids constraints. Returned result needs to distinguish valid from invalid intervals.", "case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers and", "regardless of their validity. Interval ids do not need to be in specific", "col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct", "= testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col =", "marker_use: dict Defines the marker start/end use. \"\"\" # instantiate test case testcase_instance", "import pytest from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402 pyspark", "def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available wranglers and test cases. Parameters", "@pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ----------", "pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Contains", "@pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids constraints. Returned result needs", "= [x.__name__ for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\")", "case testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler", "data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin", "Returned result needs to distinguish valid from invalid intervals. Invalid intervals need to", "kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler to test case", ".sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test", "the marker start/end use. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") #", "# pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for", "instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5)", "= wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result", "tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate", "@CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase:", "of their validity. Interval ids do not need to be in specific order.", "case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler", "\"\"\"This module contains tests for pyspark interval identifier. isort:skip_file \"\"\" import pandas as", "import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for", "wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result =", "= wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase,", "df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col", "as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\",", "\"\"\"Tests that repartition has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the", "= wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler):", "testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass", "@pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available wranglers and", "testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform)", "Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate test", "pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific", "wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all", "begin tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") #", "need to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance", "pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics,", "test_repartition(wrangler): \"\"\"Tests that repartition has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to", "and test cases. Parameters ---------- testcase: DataTestCase Generates test data for given test", "wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def", "test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates", "distinguish intervals regardless of their validity. Interval ids do not need to be", "pytestmark = pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from", "needs to distinguish valid from invalid intervals. Invalid intervals need to be 0.", "from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS =", "instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns':", "= (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def", "@pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier", "wrangler): \"\"\"Tests correct behaviour for missing groupby columns. Parameters ---------- testcase: DataTestCase Generates", "pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against", "do not need to be in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers", "= testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas()", "df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS)", "not need to be in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to", "= wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase,", "interval identifier. isort:skip_file \"\"\" import pandas as pd import pytest from pywrangler.util.testing import", "testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters", "= testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns)", "`marker_end_use_first` parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance", "Defines the marker start/end use. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\")", "PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402", ".reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler):", "`WRANGLER`. marker_use: dict Defines the marker start/end use. \"\"\" # instantiate test case", "wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\")", "df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids constraints. Returned", "def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing groupby columns. Parameters ---------- testcase:", "ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted)", "testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has no effect. Parameters ---------- wrangler:", "as pd import pytest from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark # noqa:", "repartition has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance", ".to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def", "in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler,", "be in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance", "no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested.", "repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints. Returned result only", "dict Defines the marker start/end use. \"\"\" # instantiate test case testcase_instance =", "df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas()", "\"\"\"Tests correct behaviour for missing groupby columns. Parameters ---------- testcase: DataTestCase Generates test", "result only needs to distinguish intervals regardless of their validity. Interval ids do", "marker_use): \"\"\"Test for correct valid iids constraints. Returned result needs to distinguish valid", "# pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests", "= testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test", "specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates test data for", "argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available", "cases. Parameters ---------- testcase: DataTestCase Generates test data for given test case. wrangler:", "`marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates test data for given", "E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids )", "test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available wranglers and test cases. Parameters ----------", "\"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates test data", "wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\")", "pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct", "pd import pytest from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402", "test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers", "case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\"", "pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for", "case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints. Returned", "testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas()", "for missing groupby columns. Parameters ---------- testcase: DataTestCase Generates test data for given", "tested. See `WRANGLER`. marker_use: dict Defines the marker start/end use. \"\"\" # instantiate", "= testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct", "`marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy()", "`WRANGLER`. \"\"\" # instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance", "given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See", "col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests", "wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input)", "kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) # pass wrangler to test", "behaviour for missing groupby columns. Parameters ---------- testcase: DataTestCase Generates test data for", "= pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier", "wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" #", "the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance =", "to be in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual", "wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple()", "Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`.", "df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0))", "wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler):", "wrangler_instance = wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def", "testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour", "iids constraints. Returned result only needs to distinguish intervals regardless of their validity.", "def test_repartition(wrangler): \"\"\"Tests that repartition has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers", "Invalid intervals need to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the", "test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers and test cases. Parameters ---------- testcase:", ") from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS", "wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases", "in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin", "testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints. Returned result", "# pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests", "intervals. Invalid intervals need to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to", ") WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in WRANGLER] WRANGLER_KWARGS", "VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS)", "test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance", "# pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition", "pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple,", "wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test", "tests for pyspark interval identifier. isort:skip_file \"\"\" import pandas as pd import pytest", "CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted", "instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) # pass wrangler", "wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that", "(PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases", "= testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs)", "pyspark interval identifier. isort:skip_file \"\"\" import pandas as pd import pytest from pywrangler.util.testing", "intervals regardless of their validity. Interval ids do not need to be in", "test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`.", "Interval ids do not need to be in specific order. Parameters ---------- wrangler:", "wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs)", "= wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0))", "`WRANGLER`. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs", "ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available wranglers", "[x.__name__ for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases", "wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler):", "constraints. Returned result needs to distinguish valid from invalid intervals. Invalid intervals need", "testcase: DataTestCase Generates test data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to", "ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output", "`WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance =", "testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case", "for correct valid iids constraints. Returned result needs to distinguish valid from invalid", "their validity. Interval ids do not need to be in specific order. Parameters", "# instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy()", "def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers and test cases. Parameters ----------", "to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and", "for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def", "# instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform)", "and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use)", "Returned result only needs to distinguish intervals regardless of their validity. Interval ids", "columns. Parameters ---------- testcase: DataTestCase Generates test data for given test case. wrangler:", "test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass", "testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS)", "module contains tests for pyspark interval identifier. isort:skip_file \"\"\" import pandas as pd", "@CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers and test cases. Parameters", "Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\")", "test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None})", "See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark()", ".to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use):", "wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler to test", "Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs =", "# noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import (", "testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result", "for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested.", "testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids", "correct behaviour for missing groupby columns. Parameters ---------- testcase: DataTestCase Generates test data", "= testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) #", "\"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input", "raw iids constraints. Returned result only needs to distinguish intervals regardless of their", "parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance =", "to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available", "= ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark()", "case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance =", "the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance", "VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in", "# instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform,", "pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing groupby", "wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler):", "testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance =", "Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first`", "wranglers and test cases. Parameters ---------- testcase: DataTestCase Generates test data for given", "wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw", "case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use:", "to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids", "distinguish valid from invalid intervals. Invalid intervals need to be 0. Parameters ----------", "ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum,", "to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance", "the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Defines the marker start/end", "@CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all available wranglers and test", "case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has no effect. Parameters ----------", "invalid intervals. Invalid intervals need to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers", "wrangler): \"\"\"Tests against all available wranglers and test cases. Parameters ---------- testcase: DataTestCase", "has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin", "import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import", "missing groupby columns. Parameters ---------- testcase: DataTestCase Generates test data for given test", "marker start/end use. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate", "(VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER,", "CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum,", "= wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests", "result needs to distinguish valid from invalid intervals. Invalid intervals need to be", "case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios.", "pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Defines", "testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name", "See `WRANGLER`. marker_use: dict Defines the marker start/end use. \"\"\" # instantiate test", "= testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) # pass wrangler to test case", "( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x", "\"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance =", "constraints. Returned result only needs to distinguish intervals regardless of their validity. Interval", "VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in WRANGLER]", ".reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for", "df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing", "import PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa:", "ids do not need to be in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier", "Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Defines the", "tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate", "\"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output =", "valid from invalid intervals. Invalid intervals need to be 0. Parameters ---------- wrangler:", "# instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs)", "Generates test data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual", "= (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS)", "wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) # pass wrangler to", "wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as", "order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See", "contains tests for pyspark interval identifier. isort:skip_file \"\"\" import pandas as pd import", "wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS)", "# instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) # pass", "pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has", "dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs", "pandas as pd import pytest from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark #", "noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral,", "actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance =", "wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has no", "x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase,", "correct raw iids constraints. Returned result only needs to distinguish intervals regardless of", "MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER =", "def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids constraints. Returned result needs to", "= testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform)", "kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases", "testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to", "pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__", "instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use)", "E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd,", "need to be in specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the", "begin tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict.", "use. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs", "`WRANGLER`. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance", "intervals need to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual", "@pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing groupby columns. Parameters", "(PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler,", "identifier. isort:skip_file \"\"\" import pandas as pd import pytest from pywrangler.util.testing import PlainFrame", "WRANGLER_IDS = [x.__name__ for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS)", "to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate test case", "CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted )", "wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0),", "wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Defines the marker start/end use. \"\"\"", "wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def", "@CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids constraints. Returned result", "= pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy,", ".sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) pd.testing.assert_series_equal(df_result[col].eq(0), df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase,", "wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input)", "kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result =", "from invalid intervals. Invalid intervals need to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier", "\"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs =", "validity. Interval ids do not need to be in specific order. Parameters ----------", "test cases. Parameters ---------- testcase: DataTestCase Generates test data for given test case.", "pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\") #", "WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests", "# noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids,", "scenarios. Parameters ---------- testcase: DataTestCase Generates test data for given test case. wrangler:", "`WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output", "@CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing groupby columns. Parameters ----------", "wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates test", "= MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test", "WRANGLER = (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in WRANGLER] WRANGLER_KWARGS =", "DataTestCase Generates test data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the", "all available wranglers and test cases. Parameters ---------- testcase: DataTestCase Generates test data", "testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True))", "wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" testcase_instance", "test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids constraints. Returned result needs to distinguish", "---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\"", "noqa: E402 from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids", "---------- testcase: DataTestCase Generates test data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers", "tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier", "\"\"\" import pandas as pd import pytest from pywrangler.util.testing import PlainFrame pytestmark =", "ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result =", "for pyspark interval identifier. isort:skip_file \"\"\" import pandas as pd import pytest from", "df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result) .to_pandas() .sort_values(testcase_instance.orderby_columns) .reset_index(drop=True)) col = testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0),", "test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints.", "`marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates test data for given test case.", "# instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs)", "specific order. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested.", "to distinguish valid from invalid intervals. Invalid intervals need to be 0. Parameters", "dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against all", "test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has no effect. Parameters", "MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case", "test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing groupby columns. Parameters ---------- testcase: DataTestCase", "See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler", "**testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result)", "@pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints. Returned result only needs", "pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. \"\"\" # instantiate", "**kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result = (PlainFrame.from_pyspark(df_result)", "to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_repartition(wrangler): \"\"\"Tests that repartition has no effect.", "valid iids constraints. Returned result needs to distinguish valid from invalid intervals. Invalid", "start/end use. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler", "that repartition has no effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual", "= ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result", "testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers and test", "testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input =", "import pandas as pd import pytest from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark", "pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\") # noqa: E402 from tests.test_data.interval_identifier import", "marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\")", "test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints. Returned result only needs to distinguish", "isort:skip_file \"\"\" import pandas as pd import pytest from pywrangler.util.testing import PlainFrame pytestmark", "instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) #", "pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid iids constraints.", "for correct raw iids constraints. Returned result only needs to distinguish intervals regardless", "wrangler, marker_use): \"\"\"Tests against all available wranglers and test cases. Parameters ---------- testcase:", "test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass", "test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first`", "\"\"\"Tests against all available wranglers and test cases. Parameters ---------- testcase: DataTestCase Generates", "the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first`", "See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler", "WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use):", "begin tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input", "\"\"\"Test for correct valid iids constraints. Returned result needs to distinguish valid from", "0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See", "---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use:", "instantiate test case testcase_instance = testcase(\"pyspark\") # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) #", "@pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionIdenticalStartEnd.pytest_parametrize_testcases def test_identical_start_end(testcase, wrangler): \"\"\"Tests against all available wranglers and test cases.", "actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters", "( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import (", "and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase Generates test data for given test", "CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from pywrangler.pyspark.wranglers.interval_identifier import ( VectorizedCumSum, VectorizedCumSumAdjusted ) WRANGLER", "= wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result", "wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test.pyspark(wrangler_instance.transform, repartition=5) @pytest.mark.parametrize(**WRANGLER_KWARGS) def", "dict. \"\"\" testcase_instance = ResultTypeValidIids(\"pyspark\") kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs)", "testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs)", "groupby columns. Parameters ---------- testcase: DataTestCase Generates test data for given test case.", "\"\"\" # instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance =", "= (VectorizedCumSum, VectorizedCumSumAdjusted) WRANGLER_IDS = [x.__name__ for x in WRANGLER] WRANGLER_KWARGS = dict(argnames='wrangler',", "available wranglers and test cases. Parameters ---------- testcase: DataTestCase Generates test data for", "= dict(argnames='wrangler', argvalues=WRANGLER, ids=WRANGLER_IDS) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @CollectionGeneral.pytest_parametrize_testcases def test_base(testcase, wrangler, marker_use): \"\"\"Tests against", "to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Defines the marker", "\"\"\"Test for correct raw iids constraints. Returned result only needs to distinguish intervals", "Parameters ---------- testcase: DataTestCase Generates test data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier", "tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\"", "case testcase_instance = testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance", "to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and", "wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input = testcase_instance.input.to_pyspark() df_output = testcase_instance.output.to_pandas() df_result = wrangler_instance.transform(df_input) df_result =", "pytest from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402 pyspark =", "begin tested. See `WRANGLER`. marker_use: dict Defines the marker start/end use. \"\"\" #", "effect. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See", "= testcase_instance.target_column_name pd.testing.assert_series_equal(df_result[col].diff().ne(0), df_output[col].diff().ne(0)) @CollectionGeneral.pytest_parametrize_kwargs(\"marker_use\") @pytest.mark.parametrize(**WRANGLER_KWARGS) def test_result_type_valid_iids(wrangler, marker_use): \"\"\"Test for correct valid", "wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested. See `WRANGLER`. marker_use: dict", "See `WRANGLER`. marker_use: dict Contains `marker_start_use_first` and `marker_end_use_first` parameters as dict. \"\"\" testcase_instance", "only needs to distinguish intervals regardless of their validity. Interval ids do not", "testcase(\"pyspark\") # instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update({'groupby_columns': None}) wrangler_instance = wrangler(**kwargs) #", "against all available wranglers and test cases. Parameters ---------- testcase: DataTestCase Generates test", "wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionMarkerSpecifics.pytest_parametrize_testcases def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first`", "be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin tested.", "instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to test case testcase_instance.test(wrangler_instance.transform) @pytest.mark.parametrize(**WRANGLER_KWARGS)", "iids constraints. Returned result needs to distinguish valid from invalid intervals. Invalid intervals", "testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() # instantiate wrangler wrangler_instance = wrangler(**testcase_instance.test_kwargs) # pass wrangler to", "tested. See `WRANGLER`. \"\"\" testcase_instance = ResultTypeRawIids(\"pandas\") wrangler_instance = wrangler(result_type=\"raw\", **testcase_instance.test_kwargs) df_input =", "from tests.test_data.interval_identifier import ( CollectionGeneral, CollectionIdenticalStartEnd, CollectionMarkerSpecifics, CollectionNoOrderGroupBy, MultipleIntervalsSpanningGroupbyExtendedTriple, ResultTypeRawIids, ResultTypeValidIids ) from", "begin tested. See `WRANGLER`. \"\"\" # instantiate test case testcase_instance = MultipleIntervalsSpanningGroupbyExtendedTriple() #", "instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler to", "needs to distinguish intervals regardless of their validity. Interval ids do not need", "marker_use): \"\"\"Tests against all available wranglers and test cases. Parameters ---------- testcase: DataTestCase", "test data for given test case. wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance", "to be 0. Parameters ---------- wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier Refers to the actual wrangler_instance begin", "from pywrangler.util.testing import PlainFrame pytestmark = pytest.mark.pyspark # noqa: E402 pyspark = pytest.importorskip(\"pyspark\")", "def test_marker_specifics(testcase, wrangler): \"\"\"Tests specific `marker_start_use_first` and `marker_end_use_first` scenarios. Parameters ---------- testcase: DataTestCase", "# instantiate wrangler kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(**kwargs) # pass wrangler", "to distinguish intervals regardless of their validity. Interval ids do not need to", "df_output[col].eq(0)) @pytest.mark.parametrize(**WRANGLER_KWARGS) @CollectionNoOrderGroupBy.pytest_parametrize_testcases def test_no_order_groupby(testcase, wrangler): \"\"\"Tests correct behaviour for missing groupby columns.", "kwargs = testcase_instance.test_kwargs.copy() kwargs.update(marker_use) wrangler_instance = wrangler(result_type=\"valid\", **kwargs) df_input = testcase_instance.input.to_pyspark() df_output =", "def test_result_type_raw_iids(wrangler): \"\"\"Test for correct raw iids constraints. Returned result only needs to" ]